Passing and Assigning Objects

Before we leave the subject of PHP and objects, it is important to stress a particular difference between PHP 4 and PHP 5. In PHP 4, objects were passed to and from functions by value. Let’s pass an object around a bit to test this process:

class PassObj {
  function PassObj( $item ) {
    $item->name="harry";
  }
}

class Item {
  var $name = "bob";
}

$item = new Item();
$pass = new PassObj( $item );
print $item->name;

The PassObj class in the fragment has a constructor that accepts an Item object. It changes the $name property of the Item object and does nothing else. If we were to run this code with PHP 4, a copy of an Item object would be passed to the PassObj constructor. The original object would not be affected by ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.