繁体   English   中英

在用户定义的类中调用用户定义的函数

[英]Calling User Defined Function In User Defined Class

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

这是我的课程(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();
        }

为什么会这样?

. 用于concatenate 您使用->访问班级成员

$result = $mailer->SendMail();

您不要用点来调用类方法。 您可以通过->调用类方法(不是静态的),例如:

$result = $mailer->SendMail();

此外,您需要使用$this->设置属性(同样,如果不是静态的话),将构造函数的内容更改为:

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

您的mail()函数也是如此:

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

您看到我多次提到static,如果您想访问类中的static属性或方法,则可以使用self::

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM