开发者

How can I have an `factory` method inherit properly without defining the class name in PHP?

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 wi开发者_如何学Cth 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜