php5中的引用存在问题

| 让我从代码开始:
<?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致命错误:在第24行的../test.php中的非对象上调用成员函数live()” 我已经在网上搜索了一段时间,但找不到解决此问题的解决方案。 有人可以帮助我了解我对php5的不了解吗?     
已邀请:
您需要使用“ 1”来访问成员变量。此外,您必须为其分配父对象。
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);
}
    
首先,通过使用__construct关键字在PHP5中使用构造函数的首选方法。 当您访问班级成员时,您应该使用
$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
方法中对其进行设置。     

要回复问题请先登录注册