I have an abstract base class in my application.
I want to provide an factory() method to allow me to make a new model easily with a static method.
public static function factory() {
$class = __CLASS__;
return new $class;
}
This obviously doesn’t work as it tries to initiate the abstract class.
What I wanted to know, is how can I make classes which inherit this method initiate themselves and not the base class?
Do I have to pass the name of the model to the factory method?
PHP version is 5.2.13 but am also interested in knowing what I would use in >= PHP 5.3.
Do I have to pass the name of the model to the factory method? – prior to 5.3 yes.
This is a bit of an anti-pattern; typically you’d just define the method as abstract then implement on each class.
The simplest way I can explain, is to say that static methods define common functionality which is not instance or context aware, so by depending on context/instance data you’re doing something a bit wrong – consider it the same as writing
if($this->property)inside a static method.