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).

Yurii Rashkovskii
  • 1,122
  • 1
  • 10
  • 20
  • I've been seeing people complain a lot about late static binding lately and I'm curious: What other languages commonly used for web development *do* support late static binding? Python? Ruby? Perl? Java? – Ariel Arjona Dec 15 '08 at 02:39
  • all of them, afair. I used Ruby extensively over past couple of years. – Yurii Rashkovskii Dec 15 '08 at 02:46
  • possible duplicate of [Inheritance of static members in PHP](http://stackoverflow.com/questions/532754/inheritance-of-static-members-in-php) – hakre Jul 01 '12 at 15:43

2 Answers2

4

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__);}
}
Alexei Tenitski
  • 9,030
  • 6
  • 41
  • 50
  • 2
    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 Oct 22 '09 at 00:46
3

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
  • 17,379
  • 7
  • 50
  • 64