Patrique Ouimet
Senior Product Engineer
Sat, May 2, 2020 12:27 PM
In this short article we'll take a look at the difference between new self and new static as it relates to inheritance in PHP. When you call new self it will always reference the class in which it is defined, where as new static will reference the calling class.
Let's look at some examples
<?php
class ParentClass
{
public static function create()
{
return new self();
}
}
class ChildClass extends ParentClass
{
}
echo get_class(ParentClass::create()) . PHP_EOL;
echo get_class(ChildClass::create()) . PHP_EOL;If we run the above file php index.php, the output will look like:
ParentClass
ParentClass
As we can see from the output regardless of the calling class it references the parent where new self is defined.
Let's modify the file to use new static
<?php
class ParentClass
{
public static function create()
{
return new static();
}
}
class ChildClass extends ParentClass
{
}
echo get_class(ParentClass::create()) . PHP_EOL;
echo get_class(ChildClass::create()) . PHP_EOL;Let's run this again php index.php, now the output looks like this:
ParentClass
ChildClass
As we can see from the output using new static references the calling class instead of the class where the new call is defined.