addRecipients使用push_array但它不起作用。我在这做错了什么?
在class.emailer.php
中class Emailer
{
public $sender;
public $recipients;
public $subject;
public $body;
function __construct($sender)
{
$this->sender = $sender;
$this->recipients = array();
}
public function addRecipients($recipient)
{
array_push($this->recipients, $recipient);
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function setBody($body)
{
$this->body = $body;
}
public function sendEmail()
{
echo "From sendEmail, send email initiated<br />";
echo "Body: ".$this->body."<br />";
echo "Subject: ".$this->subject."<br />";
print_r ($this->sender);
print_r ($this->recipients);
echo "<br />";
foreach ($this->recipients as $recipient)
{
echo "6<br />";
//$result = mail($recipient, $this->subject, $this->body,"From: {$this->sender}\r\n");
echo "7<br />";
if ($result) echo "Mail successfully sent to {$recipient}<br/>";
}
}
}
在class.extendedemailer.php
中include_once("class.emailer.php");
class ExtendedEmailer extends emailer
{
function __construct(){
//overwriting __contruct here
}
public function setSender($sender)
{
$this->sender = $sender;
}
}
并在sendemail.php
include_once("class.extendedemailer.php");
echo "start 1<br />";
$xemailer = new ExtendedEmailer();
echo "1. adding sender: <br />";
$xemailer->setSender("sender@mywebsite.com");
print_r ($xemailer->sender);
echo "<br />2. adding recipients: <br />";
$xemailer->addRecipients("recipientemail@gmail.com");
var_dump ($xemailer->recipients);
echo "<br />3. adding subject: <br />";
$xemailer->setSubject("Just a Test<br />");
print_r ($xemailer->subject);
echo "4. adding body<br />";
$xemailer->setBody("Hi, How are you?<br />");
print_r ($xemailer->body);
echo "5. sending email<br />";
$xemailer->sendEmail();
收件人的输出为NULL。
start 1
1. adding sender:
sender@mywebsite.com
2. adding recipients:
NULL
3. adding subject:
Just a Test
4. adding body
Hi, How are you?
5. sending email
From sendEmail, send email initiated
Body: Hi, How are you?
Subject: Just a Test
答案 0 :(得分:4)
当你重写构造函数时,你可能不会发起$recipients
。
class Emailer {
public $recipients = array();
function __construct($sender)
{
$this->sender = $sender;
}
应该这样做。检查您的警告
警告:array_push()期望参数1为数组,在......
中给出null
答案 1 :(得分:2)
您需要从ExtendedEmailer的构造函数中调用父的构造函数。
class ExtendedEmailer extends emailer
{
function __construct(){
parent::__construct(null);
}
// ...
}
否则$recipients
永远不会被初始化为数组。
答案 2 :(得分:2)
问题是你覆盖了Email
类的构造函数而从不调用它(parent::__construct()
)。在ExtendedEmailer
类构造函数中调用父构造函数,或者如果您实际上没有使用它,则从ExtendedEmailer
中完全删除构造函数(在示例代码中,您不是)。
答案 3 :(得分:1)
您错过了调用子构造函数中的父构造函数
class ExtendedEmailer extends emailer
{
function __construct(){
//overwriting __contruct here
parent::__construct('dummy_sender@sender.com');
}
}
应解决此问题。
答案 4 :(得分:0)
只做
public $recipients = array();
而不仅仅是那种裸体
public $recipients;
这就是全部,而且作为一个额外的,你可以随心所欲地填补你的建造者。 - 您怎么看?
问候,M。