Adam Baranyai
Adam Baranyai

Reputation: 3867

PHP Object oriented programming - access parent element from child

Let's propose we have the following classes, and the following code:

class ParentClass {
    public $x;
    public $child;

    public function __construct($x) {
        $this->x=$x;
        $this->child=new ChildClass();
    }
}

class ChildClass extends ParentClass {

    public function __construct() {

    }

    public function tellX() {
        echo $this->x;
    }
}

$parent1=new ParentClass('test');
$parent2=new ParentClass('test2');
echo $parent1->child->tellX();
echo "<BR>";
echo $parent2->child->tellX();

This outputs two empty lines for me. Is there any possibility, to create a new object(objChild), inside of an object(objParent), and access the non-static properties of objParent from objChild?

Upvotes: 1

Views: 109

Answers (1)

William_Wilson
William_Wilson

Reputation: 1264

What you are describing is possible, but what you are failing to understand is that the child object created in the parent's constructor derives from parent, but it is a different instance of parent than the one creating the child.

Try this example for a better understanding:

class ParentClass {
    public $x;
    public $child;

    public function __construct($x) {
        $this->setX( $x );
        $this->child = new ChildClass( $x + 1 );
    }

    function setX( $x )
    {
        $this->x = $x;
    }

    public function tellX() {
        echo $this->x;
    }
}

class ChildClass extends ParentClass {

    public function __construct( $x )
    {
        $this->setX( $x );
    }
}

$parent1=new ParentClass(1);
$parent2=new ParentClass(2);
$parent1->tellX();
echo "<BR>";
$parent1->child->tellX();
echo "<BR>";
$parent2->child->tellX();
echo "<BR>";
$parent2->tellX();

Notice that the parent and parent's contained child do not have the same x value, but children inherit the tellX function from parent even though they have not defined it themselves.

Traditionally you would create an instance of the child class which inherits values/functions from the parent instead of creating a new instance of a child from the parent.

An important thing to note about the parent/child relationship in PHP is that member variables are not inherited. Thus why I've implemented the setX function in the parent to fake this behaviour.

Upvotes: 1

Related Questions