Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new instance of class being called rather than parent

How can I return an instance of the class being called, when the method is in a parent class.

Eg. In the example below, how can I return an instance of B if I call B::foo();?

abstract class A
{
    public static function foo()
    {
        $instance = new A(); // I want this to return a new instance of child class.
             ... Do things with instance ...
        return $instance;
    }
}

class B extends A
{
}

class C extends A
{
}

B::foo(); // Return an instance of B, not of the parent class.
C::foo(); // Return an instance of C, not of the parent class.

I know I can do it something like this, but is there a neater way:

abstract class A
{
    abstract static function getInstance();

    public static function foo()
    {
        $instance = $this->getInstance(); // I want this to return a new instance of child class.
             ... Do things with instance ...
        return $instance;
    }
}

class B extends A
{
    public static function getInstance() {
        return new B();
    }
}

class C extends A
{
    public static function getInstance() {
        return new C();
    }
}
like image 219
Adam Avatar asked Oct 28 '25 06:10

Adam


2 Answers

$instance = new static;

You're looking for Late Static Binding.

like image 161
deceze Avatar answered Oct 31 '25 00:10

deceze


http://www.php.net/manual/en/function.get-called-class.php

<?php

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

?>

Result

string(3) "foo"
string(3) "bar"

So your function is going to be:

public static function foo()
{
    $className = get_called_class();
    $instance = new $className(); 
    return $instance;
}
like image 42
E_p Avatar answered Oct 30 '25 23:10

E_p



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!