在用户定义中调用用户定义函数 Class
Calling User Defined Function In User Defined Class
我正在尝试创建一个自定义 class 来为我处理邮件。
这是我的 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) 我收到 "Call to undefined function 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
。您使用 ->
访问 class
的成员
$result = $mailer->SendMail();
您不能用点调用 class 方法。您使用 ->
调用 class 方法(非静态),例如:
$result = $mailer->SendMail();
此外,您需要使用 $this->
设置您的属性(同样,如果不是静态的)将您的构造函数的内容更改为:
$this->to = $to;
$this->subject = $subject;
$this->message = $message;
您的 mail()
函数也是如此:
mail($this->to, $this->subject, $this->messagecontent)
你看到我多次提到静态,如果你想在你的 class 中访问静态 属性 或方法,你可以使用 self::
.
是联系运算符,要访问 class 变量和函数的成员,请使用 ->
运算符
使用以下代码:
$result = $mailer->SendMail();
我正在尝试创建一个自定义 class 来为我处理邮件。
这是我的 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) 我收到 "Call to undefined function 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
。您使用 ->
访问 class
$result = $mailer->SendMail();
您不能用点调用 class 方法。您使用 ->
调用 class 方法(非静态),例如:
$result = $mailer->SendMail();
此外,您需要使用 $this->
设置您的属性(同样,如果不是静态的)将您的构造函数的内容更改为:
$this->to = $to;
$this->subject = $subject;
$this->message = $message;
您的 mail()
函数也是如此:
mail($this->to, $this->subject, $this->messagecontent)
你看到我多次提到静态,如果你想在你的 class 中访问静态 属性 或方法,你可以使用 self::
.
是联系运算符,要访问 class 变量和函数的成员,请使用 ->
运算符
使用以下代码:
$result = $mailer->SendMail();