类继承中的未定义属性?

时间:2015-10-21 18:33:25

标签: php

我刚开始学习OOP PHP,并且我已经完成了一些练习,并且我遇到了返回这些错误的继承类的问题:

Notice: Undefined property: HtmlEmailer::$recipients in C:\xampp\htdocs\class.htmlemailer.php on line 10

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\class.htmlemailer.php on line 10

为什么是Undefined Property?我确实在emailer.test.php中定义了它......

我确实阅读了本书同一章的3倍,检查了代码的每一部分,我没有意识到错误的位置。

我的代码是:class.emailer.php

<?php
/**
* 
*/
class Emailer
{
    private $sender;
    private $recipients;
    private $subject;
    private $body;

    function __construct($sender)
    {
        $this->sender = $sender;
        $this->recipients = array();
    }

    public function addRecipients($recipients)
    {
        array_push($this->recipients, $recipients);
    }

    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 "Email successfully sent to ".$recipient;
            }
        }
    }
}

?>

class.htmlemailer.php

<?php
/**
* htmlemailer extends emailer
*/

class HtmlEmailer extends Emailer
{
    public function sendHTMLEmail()
    {
        foreach ($this->recipients as $recipient)
        {
            $headers = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
            $headers .= 'From: {$this->sender}' . "\r\n";

            $result = mail($recipient, $this->subject, $this->body, $headers);
            if ($result)
            {
                echo "HTML mail successfully sent to ".$recipient." ! <br />";
            }
        }
    }
}

?>

emailer.test.php

<html>

<?php 
/**
 * tests
 */
include_once('class.emailer.php');
include_once('class.htmlemailer.php');

$emailerobject = new HtmlEmailer('some@emaildotcom');
$emailerobject->addRecipients('user@emaildotcom');
$emailerobject->setSubject('Some Subject');
$emailerobject->setBody('Some body message');
$emailerobject->sendHTMLEmail();

?>

</html>

2 个答案:

答案 0 :(得分:2)

你必须改变

don't

private $recipients;

使属性可以在子类中访问。

请阅读有关visibility in PHP OOP

的php文档

答案 1 :(得分:1)

您不能继承私有财产,只能受到保护或公开。如果您希望下级类继承按private更改protected,那么它们将是可访问的。

class Emailer
{
    protected $sender;
    protected $recipients;
    protected $subject;
    protected $body;