See the following example (PHP)
class Parent
{
protected $_property;
protected $_anotherP;
public function __construct($var)
{
$this->_property = $var;
$this->someMethod(); #Sets $_anotherP
}
protected function someMethod()
...
}
class Child extends Parent
{
protected $parent;
public function __construct($parent)
{
$this->parent = $parent;
}
private function myMethod()
{
return $this->parent->_anotherP; #Note this line
}
}
I am new to OOP and am a bit ignorant.
Here to access the parents property I am using an instance of that class, which seems wrong :S (no need of being i child then). Is there an easy way, so that i can sync the parent properties with the child properties and can directly access $this->anotherP without having to use $this->parent->anotherP ?
As your
Childclass is extending yourParentclass, every properties and methods that are eitherpublicorprotectedin theParentclass will be seen by theChildclass as if they were defined in theChildclass — and the other way arround.When the
ChildclassextendstheParentclass, it can be seen as “Childis aParent“ — which means theChildhas the properties of theParent, unless it redefines those another way.(BTW, note that “
parent” is a reserved keyword, in PHP — which means you can’t name a class with that name)Here’s a quick example of a “parent” class :
And it’s “child” class :
That can be used this way :
And you’ll get as output :
Which means the
$dataproperty, defined in theMyParentclass, and initialized in a method of that sameMyParentclass, is accessible by theChildclass as if it were its own.To make things simple : as the
Child“is a”MyParent, it doesn’t need to keep a pointer to… itself 😉