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 ?
This may save you a few hours of searching around.
Remember: Your Child class only inherits the properties DEFINED in the Parent class... So if you instantiate an object using Parent class and then populate it with data, then this data will NOT be available in your child class...
It's super obvious of course, but I'm guessing others may run into the same issue.
A super simple solution is not to extend anything, simply pass the $object of your parent class into your child class through a constructor. This way you have access to all the properties and methods of the object generated by parent class
Example
If your $parentObject has a public property $name, then you can access it inside the child class with a function like:
As your
Child
class is extending yourParent
class, every properties and methods that are eitherpublic
orprotected
in theParent
class will be seen by theChild
class as if they were defined in theChild
class -- and the other way arround.When the
Child
classextends
theParent
class, it can be seen as "Child
is aParent
" -- which means theChild
has 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
$data
property, defined in theMyParent
class, and initialized in a method of that sameMyParent
class, is accessible by theChild
class 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 ;-)