开发者

Problem with references in php5

开发者 https://www.devze.com 2023-02-26 19:55 出处:网络
Let me start right off the code: <?php class Father{ function Father(){ echo \'A wild Father appears..\';

Let me start right off the code:

<?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();

?>

When running this I get an error on Line 24 saying "PHP Fatal error: Call to a member function live() on a non-object in ..开发者_开发知识库/test.php on line 24" I've searched the web for a while now and can't find a solution for this to work. Can someone help me with my poor understanding of php5?


You need to use $this->parent->live() to access the member variable. Additionally, you have to assign the parent object to it.

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();
    }
}

Besides that, you should rename your constructor methods to __construct which is the suggested name in PHP5.


You didn't call setParent in your constructor.
This will fix it:

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


First, the preferred method to use constructor in PHP5 by using __construct keyword. When you access to class member you should to use $this, witch in your case you didn't when you tried to parent member.

function setParent($p){
        $parent = $p;
    }

Make it like this:

function setParent($p){
        $this->parent = $p;
    }

And this:

   function dance(){
        echo 'The child is dancing, when ';
        $parent -> live();
    }

To this:

   function dance(){
        echo 'The child is dancing, when ';
        $this->parent -> live();
    }

You will be end with this:

$p = new Father();
$p -> live();
$c = new Child();
$c -> setParent($p);
$c -> dance();

You don't need pass the parent to the child constructor as you will set it in setParent method.

0

精彩评论

暂无评论...
验证码 换一张
取 消