Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an already-made object be re-created (see example)

Tags:

oop

php

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.

like image 897
ʎɹnɔɹǝW Avatar asked Nov 08 '22 03:11

ʎɹnɔɹǝW


1 Answers

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().

like image 73
Rei Avatar answered Nov 15 '22 10:11

Rei