我剛開始學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
爲什麼是未定義的屬性?我的確在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('[email protected]');
$emailerobject->addRecipients('[email protected]');
$emailerobject->setSubject('Some Subject');
$emailerobject->setBody('Some body message');
$emailerobject->sendHTMLEmail();
?>
</html>
問題就迎刃而解了。感謝rray和mapek。 PS:即時閱讀http://php.net/manual/en/language.oop5.visibility.php現在。 – wdarking
我也遇到過這個問題,谷歌搜索一個解決方案把我帶到這裏,這反過來解決了這個問題(感謝rray,mapek和wdarking),並揭示了另一個小問題:在文件「class.htmlemailer.php」下面的行$ emailerobject-> setbody('some body mesage');你需要添加$ emailerobject-> sendEmail();或執行代碼後,您將顯示一個空白的白頁,並且不會發送電子郵件。 – MartinJJ