【问题标题】:Calling User Defined Function In User Defined Class在用户定义的类中调用用户定义的函数
【发布时间】:2015-06-01 09:47:33
【问题描述】:

我正在尝试创建一个自定义类来为我处理邮件。

这是我的课(mailerclass.php):

class Mailer {

        // Private fields
        private $to;
        private $subject;
        private $message;

        // Constructor function
        function __construct($to, $subject, $message) {
            $to = $to;
            $subject = $subject;
            $message = $message;
        }   

        // Function to send mail with constructed data.
        public function SendMail() {

            if (mail($to, $subject, $messagecontent)) {
                return "Success";
            }
            else {
                return "Failed";    
            }           
        }

    }

当我尝试在此处调用它 (index.php) 时,我收到“调用未定义函数 SendMail()”消息?

if ($_SERVER['REQUEST_METHOD'] == "POST") {

        // Import class
        include('mailerclass.php');

        // Trim and store data
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $message = trim($_POST['message']);


        // Store mail data
        if ($validated == true) {

            // Create new instance of mailer class with user data
            $mailer = new Mailer($to, $subject, $message);          

            // Send Mail and store result
            $result = $mailer.SendMail();
        }

为什么会这样??

【问题讨论】:

  • $mailer->sendMail() 。在 php 中,您使用箭头 (->) 而不是点 (.) 调用方法,点 (.) 用于在 php 中连接。
  • 从这里开始 php.net/manual/en/language.oop5.php 在 PHP 中你使用 '->' 而不是 '.'访问对象的方法、属性。

标签: php function class methods


【解决方案1】:

你不能用点来调用类方法。您使用-> 调用类方法(非静态),例如:

$result = $mailer->SendMail();

除了你需要用$this-> 设置你的属性(如果不是静态的)改变你的contstructor的内容:

$this->to = $to;
$this->subject = $subject;
$this->message = $message;

mail() 函数也是如此:

mail($this->to, $this->subject, $this->messagecontent)

你看到我多次提到静态,如果你想在你的类中访问静态属性或方法,你可以使用self::

【讨论】:

    【解决方案2】:

    . 用于concatenate。您使用-> 访问类成员

    $result = $mailer->SendMail();
    

    【讨论】:

      【解决方案3】:

      . 是一个联系运算符,要访问一个类的成员变量和函数都使用-> 运算符 使用以下代码:
      $result = $mailer->SendMail();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多