How the re-created object will be created (see. Example)

I looked at the OOP Basics and saw this code (simplified it a bit)

You can see this class and output

class Test{} $a = new Test(); $b = new $a; var_dump($b == $a); // true 

What I don't understand is $b = new $a , but $a already an object, since / why does this work? If I do vardump $a , the output is:

 object(Test)#1 (0) { } 

So how does this variable work with the new keyword. I thought that we can only use new with an already defined class or with a string that points to an ex class:

 $var = 'Test'; new $var; // ok 

but in this case $var is a string, not another object.

+5
source share
1 answer

This is a shortcut to create a new object. Before PHP 5.3.0, you should do this:

 $class = get_class($instance); $newInstance = new $class; 

Starting with PHP 5.3.0 you can do the same with this:

 $newInstance = new $instance; 

Very useful, in my opinion, because it eliminates the need for a temporary variable.

To clarify, this creates a new object. This is not cloning. In other words, __construct() will be called instead of __clone() __construct() .

+1
source

Source: https://habr.com/ru/post/1262757/


All Articles