让我从代码开始:
<?php
class Father{
function Father(){
echo 'A wild Father appears..';
}
function live(){
echo 'Some Father feels alive!';
}
}
class Child{
private $parent;
function Child($p){
echo 'A child is born :)';
}
function setParent($p){
$parent = $p;
}
function dance(){
echo 'The child is dancing, when ';
$parent -> live();
}
}
$p = new Father();
$p -> live();
$c = new Child($p);
$c -> dance();
?>
当运行这个程序时,我在第24行得到一个错误,说"PHP致命错误:在./test.php中的非对象上调用成员函数live()在第24行"我已经在网上搜索了一段时间了,现在找不到一个解决方案。有人可以帮助我与我的php5的理解差吗?
需要使用$this->parent->live()
来访问成员变量。此外,您必须将父对象分配给它。
class Child{
private $parent;
function __construct($p){
echo 'A child is born :)';
$this->parent = $p; // you could also call setParent() here
}
function setParent($p){
$this->parent = $p;
}
function dance(){
echo 'The child is dancing, when ';
$this->parent -> live();
}
}
除此之外,您应该将构造函数方法重命名为__construct
,这是PHP5中建议的名称。
你没有在构造函数中调用setParent
。
这将修复它:
function Child($p){
echo 'A child is born :)';
$this->setParent($p);
}
首先,PHP5中使用__construct关键字来使用构造函数的首选方法。当你访问类成员时,你应该使用$this
,而在你的情况下,当你试图访问parent
成员时,你没有。
function setParent($p){
$parent = $p;
}
像这样写:
function setParent($p){
$this->parent = $p;
}
:
function dance(){
echo 'The child is dancing, when ';
$parent -> live();
}
:
function dance(){
echo 'The child is dancing, when ';
$this->parent -> live();
}
你将以这句话结束:
$p = new Father();
$p -> live();
$c = new Child();
$c -> setParent($p);
$c -> dance();
您不需要将父构造函数传递给子构造函数,因为您将在setParent
方法中设置它。