PHP’s handling of objects was completely rewritten in PHP 5 to improve performance and conform to standards common to other object-oriented languages. Aside from a long list of new features, the biggest change from PHP 3 and 4 is the way objects and their properties are handled. Take the following line of code:
In PHP 3 and 4, this makes a copy of $objectA and stores it as $objectB. Both objects then act independently of each other; changes made to $objectA don’t affect $objectB, and vice versa. This is known as copying by value and is the way PHP handles variables. In short, PHP 3 and 4 treated objects like any other variable.
Since PHP 5, objects are treated differently from other variables. Instead of making a copy of $objectA, the previous line of code stores a reference to $objectA in $objectB. Both variables refer to the same object; changes made to one affect the other. This is known as copying by reference. If you find this difficult to grasp, it’s like adopting a nickname in an online forum. In public, you might call yourself Haven’tAClue, but you remain the same person. To make a copy of an object since PHP 5, you need to use the clone keyword like this:
$objectB = $objectA;
In PHP 3 and 4, this makes a copy of $objectA and stores it as $objectB. Both objects then act independently of each other; changes made to $objectA don’t affect $objectB, and vice versa. This is known as copying by value and is the way PHP handles variables. In short, PHP 3 and 4 treated objects like any other variable.
Since PHP 5, objects are treated differently from other variables. Instead of making a copy of $objectA, the previous line of code stores a reference to $objectA in $objectB. Both variables refer to the same object; changes made to one affect the other. This is known as copying by reference. If you find this difficult to grasp, it’s like adopting a nickname in an online forum. In public, you might call yourself Haven’tAClue, but you remain the same person. To make a copy of an object since PHP 5, you need to use the clone keyword like this:
$objectB = clone $objectA;