I am using the NetBeans editor. In the following code, there is no error, but I am confused about something: why do we return new static
?
class test {
static public function getnew(){
return new static;
}
}
class child extends test {}
$obj1 = new test ();
$obj2 = new $obj1;
var_dump($obj1!==$obj2);
$obj3 = test::getnew();
var_dump($obj3 instanceof test);
$obj4 = child::getnew();
var_dump($obj4 instanceof child );
The resulting output:
boolean true
boolean true
boolean true
So what is the return new static
doing here?
return new static;
is instantiating the class "test" with late static binding. So when you extend the class "test" this will give you an instance of the extended class. Very handy for using it as a static factory method.
This is part of Late Static Bindings, introduced in PHP 5.3.
Essentially, the static
keyword will be replaced by the current class at runtime. So in case of child
it will evaluate as:
static public function getnew(){
return new child;
}
The problem with using __CLASS__
or self
is that they are replaced at compile time. So if you were to do new self;
they would always return an instance of the test
class (where the getnew()
function is defined), even if the method is called on a child class. The static
keyword is there to prevent exactly that.
The main reason for wanting to use this is so you don't have to override getnew
in every child class.