Is there any possibility to call a extension classes method from the base class constructor?
Here is an example of what I want to do:
<?php
class SomeController extends Controller {
public function init() {
echo "lol";
}
}
class Controller {
public function __construct() {
// do something to call init() in SomeController.
}
}
Just wondering is something like this possible.
Superclasses can't know anything about their own subclasses, except for the constraints that being a subclass of the superclass imposes on the subclass. If you think about it for a bit, that makes perfect sense. How could they? A developer could add anything they want to a subclass after all.
What a superclass can do, however, is enforce what methods its subclasses have. If a method exists in a superclass, then it must exist in the subclass because you can't remove methods in subclasses. If you're using a concrete superclass as your base class, then you simply have to implement a method that does nothing in the superclass, and all the subclasses will have it. For any subclass that needs something to happen in that method, they can override it with their own implementation. You can call the method from the superclass and be certain that the subclass has an implementation of it.
For this to work, the method can't be private. It has to be protected or public.
class Controller {
protected function init () {
// Do nothing, this method exists only to be overridden
}
public function __construct() {
// do something to call init() in SomeController.
$this -> init ();
}
}
If it doesn't make sense for the superclass to exist in its own right then you can make the superclass init an abstract method, so you don't have to provide an implementation at all. You can only declare abstract methods in abstract classes though, and abstract classes can't be instantiated.
Any subclass that inherits from the superclass will now be forced to implement an init() method. If it doesn't, then a fatal error will occur when you try to run your code.
abstract class Controller {
abstract protected function init ();
public function __construct() {
// do something to call init() in SomeController.
$this -> init ();
}
}
As in the earlier example, this ensures that all subclasses of this one have an init() method and it's therefore safe to call init() from the superclass.
NOTE: Due to the peculiarities of how PHP's Zend Engine is implemented, it's theoretically possible to call subclass methods from superclasses when the superclass doesn't know about the subclass method. However, this is not a deliberate design decision, it's undocumented behaviour. It therefore could be removed at any point. Even if PHP remains that way forever, it's still a very bad practice to be calling subclass methods from the superclass without knowing for certain that the subclass implements that method. Don't ever depend on that behaviour.