tags:

views:

150

answers:

2

I have the following code:


abstract class AbstractParent {
 function __construct($param) { print_r($param); }
 public static function test() { return new self(1234); }
}

class SpecificClass extends AbstractParent {}

When I invoke SpecificClass::test(), I am getting an error:

Fatal error: Cannot instantiate abstract class AbstractParent

So what I basically want is just to let AbstractParent's test() instantiate class where this test() was called from (so, in my example, instantiate SpecificClass).

Or is PHP is soooo lousy that it can't do this? :-\

+3  A: 

You can do it in PHP 5.3, which is still in alpha. What you're looking for is called Late-Static-Binding. You want the parent class to refer to the child class in a static method. You can't do it yet, but it's coming...

Edit: You can find more info here - http://www.php.net/manual/en/language.oop5.late-static-bindings.php

dave mankoff
+3  A: 

Prior version 5.3 Only with the following work around:

abstract class AbstractParent {
 function __construct($param) { print_r($param); }
 abstract public static function test();
 private static function test2($classname) { return new $classname(1234); }
}

class SpecificClass extends AbstractParent {
 public static function test() {return self::test2(__CLASS__);}
}
alexeit
You don't have to have the two static methods named differently. You can call them "test" in both classes and have SpecificClass::test return parent::test.
grantwparks