Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 516
Martynas Januškauskas Avatar asked Aug 06 '26 01:08

Martynas Januškauskas


1 Answers

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

like image 75
Chin Leung Avatar answered Aug 08 '26 17:08

Chin Leung



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!