If I have an abstract class like this:
abstract class MyApp
{
public function init()
{
$this->stuff = $this->getStuff();
}
public function getStuff()
{
return new BlueStuff();
}
}
And then I have a class that extends from this abstract class like this:
class MyExtendedClass extends MyApp
{
public function init()
{
parent::init();
}
public function getStuff()
{
return new RedStuff();
}
}
If I do:
$myobj = new MyExtendedClass();
$myobj->init();
Why does the method getStuff from the child class get called? Isn’t $this in the context of the abstract class? If so, shouldn’t the method of the abstract class get called?
Thanks!
New answer
In PHP you can use subclasses as if all methods in the parent class that don’t exist in the subclass have been copied to the subclass. So your example would be the same as:
Just think of the subclass as having all code of the parent class and you’re normally all right. There is one exception to this rule: properties. A
privateproperty of a class can only be accessed by that class, subclasses can’t access theprivateproperties of parent classes. In order to do that you need to change theprivateproperty into aprotectedproperty.Original answer
Abstract classes in PHP are just like regular classes with one big difference: they can’t get initiated. This means you can’t do
new AbstractClass();.Since they work exactly like regular classes for everything else, this also is the case for extending classes. This means that PHP first tries to find the method in the initiated class, and only looks in the abstract classes if it doesn’t exist.
So in your example this would mean that the
getStuff()method fromMyExtendedClassis called. Furthermore, this means you can leave out theinit()method inMyExtendedClass.