[英]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.