父類調用:PHP - 父類的構造函數沒有被從子類
<?php
class Emailer {
protected $sender;
private $recipients;
private $subject;
private $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()
{
foreach($this->recipients as $recipient)
{
$result = mail($recipient, $this->subject, $this->body, "From: {$this->sender}\r\n");
if($result)
echo "Mail successfully sent to {$recipient}" . "<br/>";
}
}
}
子類:
<?php
class ExtendedEmailer extends Emailer {
function __construct() {}
public function setSender($sender)
{
$this->sender = $sender;
}
}
現在我這樣做
include_once("classes/class.emailer.php");
include_once("classes/class.extendedemailer.php");
$xemailer = new ExtendedEmailer();
$xemailer->setSender("[email protected]");
$xemailer->addRecipients("[email protected]");
$xemailer->setSubject("Just a Test");
$xemailer->setBody("Hi person1, How are you?");
$xemailer->sendEmail();
但這給我以下錯誤...
Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\oop\classes\class.emailer.php on line 19
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\oop\classes\class.emailer.php on line 34
但是當我招行$this->recipients = array();
addRecipient
方法它的工作範圍內。這意味着父類的構造函數不會被調用。這個概念是在創建任何對象時用空數組初始化$recipient
變量。這是否是正常行爲?
修改父類:
<?php
class Emailer {
protected $sender;
private $recipients;
private $subject;
private $body;
function __construct($sender)
{
$this->sender = $sender;
}
public function addRecipients($recipient)
{
$this->recipients = array();
array_push($this->recipients, $recipient);
}
public function setSubject($subject)
{
$this->subject = $subject;
}
public function setBody($body)
{
$this->body = $body;
}
public function sendEmail()
{
foreach($this->recipients as $recipient)
{
$result = mail($recipient, $this->subject, $this->body, "From: {$this->sender}\r\n");
if($result)
echo "Mail successfully sent to {$recipient}" . "<br/>";
}
}
}
這給出了以下的輸出:
Mail successfully sent to [email protected]
什麼其實我試圖做的是學習如何訪問父類的protected屬性來自小孩班。在這種情況下,這是$sender
。
你應該打電話給你的父類的構造明確用'父:: __結構();' –