![](/img/trans.png)
[英]Is it mandatory to call parent::__construct from the constructor of child class in PHP?
[英]php - constructor of parent class is not being invoked from child class
父类:
<?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("someone@example.com");
$xemailer->addRecipients("person1@example.com");
$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 person1@example.com
我实际上要做的是学习如何从子类访问父类的受保护属性。 在这种情况下,哪个是$sender
。
你必须使用parent::__construct();
在子构造函数中
class ExtendedEmailer extends Emailer {
function __construct($sender)
{
parent::__construct($sender);
}
public function setSender($sender)
{
$this->sender = $sender;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.