【问题标题】:Problem with references in php5php5中的引用问题
【发布时间】:2011-04-15 23:56:10
【问题描述】:

让我从代码开始:

<?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 的了解不足的问题吗?

【问题讨论】:

  • 你知道在 PHP5 中构造函数应该命名为 __construct 而不是 NameOfTheClass 吗?
  • 不,我没有。我只是在学习这门语言,因为我必须为一个项目写一些东西。谢谢你的建议:)

标签: php class object reference


【解决方案1】:

您需要使用$this-&gt;parent-&gt;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 中的建议名称。

【讨论】:

  • 啊!很高兴知道 :) - 距离这可能成为解决方案还有 9 分钟 ^^
【解决方案2】:

您没有在构造函数中调用 setParent
这将解决它:

function Child($p){
    echo 'A child is born :)';
    $this->setParent($p);
}

【讨论】:

  • 通常getter/setter用于外部接口,内部直接访问字段更好。
【解决方案3】:

首先,在 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 方法中设置它。

【讨论】:

    猜你喜欢
    • 2010-09-16
    • 2016-09-08
    • 1970-01-01
    • 2017-05-27
    • 2012-06-13
    • 1970-01-01
    • 2021-01-03
    • 2021-01-28
    • 2012-04-26
    相关资源
    最近更新 更多