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();
}
}
$instance = new static;
You're looking for Late Static Binding.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With