通过扩展类调用时,array_push()失败

时间:2016-02-24 16:42:43

标签: php

我是PHP OOP的新手。我在书中找到了以下代码。

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); //error shown>>>array_push() expects parameter 1 to be array, null given
    }
    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/>";
    }
    }
    }

$mailer=new Emailer("dalkum@creation.com");
$mailer->addRecipients("popy@youre.com");
$mailer->setSubject("good subject");
$mailer->setBody("Test mail");

class ExtendedEmailer extends emailer
    {
    function __construct(){}
        public function setSender($sender)
        {
    $this->sender = $sender;
        }
    }

$xemailer = new ExtendedEmailer();
$xemailer->setSender("dalim@creation.com");
$xemailer->addRecipients("rabbi@rmail.net");
$xemailer->setSubject("Just a Test");
$xemailer->setBody("Hi there Dalim, How are you?");
$xemailer->sendEmail();

代码在对象$emailer中运行良好,但当我扩展到ExtendedEmailer时,它会生成消息

  

&#34;警告:array_push()期望参数1为数组,在给定的位置为null   第52行&#34; C:\ xampp \ htdocs \ session \ index.php对象   $ xemailer。

任何人都可以帮助我定义继承的问题或对象创建的问题吗?

2 个答案:

答案 0 :(得分:0)

您正在覆盖子类中的构造函数,因此$this->recipients = array();永远不会完成,变量只是null。您可以将$ recipients的声明更改为此private $recipients = array();,而不是覆盖构造函数或在自定义代码后调用parent-constructor。

答案 1 :(得分:0)

问题是$this->recipients类成员在Emailer类的构造函数中初始化,但是当你创建{{1}时,你永远不会调用那个构造函数所以它永远不会被初始化。通常,您希望子类的构造函数调用基类的构造函数,例如在ExtendedEmailer的构造函数中:

ExtendedEmailer

但我们的问题是我们没有发件人来构建它。如果这就是我们希望我们的类行为的方式,正如我怀疑的那样,我们应该执行与基类相同的初始化:

function __construct(){
    parent::__construct(/* you need a sender here */);
}