I have an abstract superclass.
abstract class SuperClass{
public static function loadInstanceFromText(){
$instance = new self();
// do some stuff, etc.
return $instance;
}
}
obviously, calling that method is impossible when referencing SuperClass, but I also have a child
class ChildClass extends SuperClass{
}
Where I would expect it to work. I call the following function:
ChildClass::loadInstanceFromText();
However, it doesn’t work, because the super is attempted to be instantiated, not ChildClass. Is there any workaround for that? Because that loadInstanceFromText is complex but basically should be the same in all inheritances.
The keyword
selfrepresents the class in which it is declared. Therefore, in this case,new self()is going to create a newSuperClass, which is impossible because it is abstract.On the other hand, the keyword
staticrepresents the calling class. This is called “Late Static Binding” and is supported since version 5.3. So, you can usenew static()which will create a newChildClassas you expect.