我正在尝试我的第一个OOP PHP,但我似乎遇到了障碍。据我所知,代码没有任何问题,我没有收到错误消息。谢谢!
<?PHP
class President {
public $lastname;
public $dob;
public $dod;
public $firstlady;
public $wikipage;
public $display;
public $party;
public $inoffice;
public function __construct ($name, $dob, $dod, $girl, $wiki, $pic, $party, $terms){
$this->lastname = $name;
$this->dob = $dob;
$this->dod = $dod;
$this->firstlady = $girl;
$this->wikipage = $wiki;
$this->display = $pic;
$this->party = $party;
$this->inoffice = $terms;
}
public function Write(){
return "President". $name . "was in office for" . $terms . "." . "He was born on" . $dob . "and" . $dod . "." . "He represented the" . $party . "and lived in the Whitehouse with his wife" .
$girl . "<br/>" . "<img src'" . $pic . "' />" . "<br />" . "<a href'" . $wiki . "'> Read more on Wikipedia</a>";
}
}
$obama = new President();
$obama->Write('Obama', 'June First 1992', 'is still alive', 'Michelle Obama', 'http://www.google.com', 'www.google.com/', 'Democrat', 'Two Terms');
echo $obama;
?>
答案 0 :(得分:2)
首先,turn on错误报告...然后..
我可以看到2个问题。
首先,你构造函数需要很多参数,当你实例化对象时,你没有传递这些参数,但是当你调用Write
方法时,它并不期望任何东西。
然后,当它返回一个字符串时,你不会回显$obama->Write(..)
。
<强>溶液强>
$obama = new President('Obama', 'June First 1992', 'is still alive', 'Michelle Obama', 'http://www.google.com', 'www.google.com/', 'Democrat', 'Two Terms');
echo $obama->Write();
假设您的参数在构造中正确,应该可以正常工作。
修改强>
如下面的评论中所述,您的write方法将无法访问任何类变量,因为它只查看本地范围。你需要改变你的变量调用:
return "President". $name
到
return "President". $this->name