Search code examples
phpoopnew-operator

PHP: new operator on an object instance creates an object instance. Why?


What is the reason the following code works and generates the given result. Is it a special language construct that is just supported by PHP? If so, then which one? Or is it just a simple php-ism?

class Foo {};

$a = new Foo();
$b = new $a();

var_dump($a); // class Foo#1 (0)
var_dump($b); // class Foo#2 (0)

Solution

  • PHP allows you to create an object instance from a variable like this:

    $a = 'Foo';
    $b = new $a;
    

    So when you use the new $a, PHP is checking if it's a string to make a new instance of the class, and if it's an object, it's going to retrieve the class name of the object instance and make a new instance from it.

    If you try to do the same with a non-string or non-object variable:

    $a = 1;
    $b = new $a;
    

    This will generate an error:

    PHP Error: Class name must be a valid object or a string

    PHP 5.3.0 introduced a couple of new ways to create instances of an object, which is an example of a scenario like you've provided:

    class Test {}
    
    $obj1 = new Test();
    $obj2 = new $obj1;
    

    For more information: Read Example #5 Creating new objects under https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new