繁体   English   中英

php5中引用的问题

[英]Problem with references in 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的不良理解吗?

您需要使用$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);
}

首先,通过使用__construct关键字在PHP5中使用构造函数的首选方法。 当您访问类成员时,应使用$this ,如果您尝试使用parent成员,则不必使用$this

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方法中对其进行设置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM