1

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?

2
  • You have 2 different objects here, which don't have anything to do with each other. Commented Oct 8, 2015 at 16:39
  • @Rizier123 Thats the correct answer, you should post it as an answer instead of a comment Commented Oct 8, 2015 at 17:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.