Let’s suppose I have a parent class in PHP like this:
class A {
private $property;
public static function factory($arg) {
$object = new A();
$object->property = $arg;
return $object;
}
}
And I want to extend it in this way:
class B extends A {
public static function factory() {
return parent::factory('constant');
}
}
When I do B::factory() I get a object of type A. What if I want an object of type B? I cannot change anything in the code of class A.
1st version
That’s because you hardcoded the
Aclass in the factory method.In class
A, instead of$object = new A()try (require Php 5.3):get_called_class()“Gets the name of the class the static method is called in.”Shorter version:
2nd version (hardcoded parent class):
Copy object properties manually:
Or use an hack to do it autoatically: