tags:

views:

25

answers:

2

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.

+1  A: 

In PHP5.3, you have "late static bindings", and with it, the function get_called_class():

$class = get_called_class();
return new $class;

Edit: Considering this is PHP5.2, there is no easy way to do it without hacking into a debug backtrace or using reflection. The problem is that "self" doesn't downreference.

Mike Sherov
+1  A: 

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.

nathan