Search code examples
phpstatic-methodsmultiple-constructors

self:: referring to derived class in static methods of a parent class


I liked the idea presented in this answer allowing having something like multiple constructors in PHP. The code I have is similar to:

class A {
    protected function __construct(){
    // made protected to disallow calling with $aa = new A()
    // in fact, does nothing
    }; 

    static public function create(){
        $instance = new self();
        //... some important code
        return $instance;
    }

    static public function createFromYetAnotherClass(YetAnotherClass $xx){
        // ...
    } 

class B extends A {};

$aa = A::create();
$bb = B::create();

Now I want to create a derived class B, which would use the same "pseudo-constructor", because it is the same code. However, in this case when I do not code the create() method, the self constant is the class A, so both variables $aa and $bb are of class A, while I wish $bb be class B.

If I use $this special variable, this of course would be class B, even in A scope, if I call any parent method from B.

I know I can copy the entire create() method (maybe Traits do help?), but I also have to copy all "constructors" (all create* methods) and this is stupid.

How can I help $bb to become B, even if the method is called in A context?


Solution

  • You want to use static, which represents the class in which the method is called. (self represents the class in which the method is defined.)

    static public function create(){
        $instance = new static();
        //... some important code
        return $instance;
    }
    

    Refer to the documentation on Late Static Bindings.

    You'll need PHP 5.3+ to use this.