I was looking at OOP Basics and saw a code like this (simplified it a bit)
You can see this class and the output
class Test{}
$a = new Test();
$b = new $a;
var_dump($b == $a); // true
What I don't understand is the $b = new $a
but $a
is already an object, so how/why does this work? If I do vardump $a
the output is:
object(Test)#1 (0) {
}
So, how can that variable work with new
keyword. I thought we could only use new
with a class that is defined already, or with a string that points to a class ex:
$var = 'Test';
new $var; // ok
but in this case, $var
is a string, not an another object.
It is a shortcut for creating new object. Before PHP 5.3.0 you have to do this:
$class = get_class($instance);
$newInstance = new $class;
As of PHP 5.3.0 you can do the same thing with this:
$newInstance = new $instance;
Very useful, in my opinion, because it eliminates the need for a temporary variable.
To clarify, this creates new object.
It is not cloning.
In other words, __construct()
will be called instead of __clone()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With