[ Team LiB ] Previous Section Next Section

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 the change, and the script would output "bob", the default $name value for Item objects.

If we were to run the code fragment in PHP 5, the script would output "harry". PHP 5 passes and assigns objects by reference rather than value. There would be only one Item object in the script, and different handles would refer to it. This behavior is more natural for an object-oriented language.

To forcibly pass and assign by reference in PHP 4, you need to do so explicitly, using the ampersand (&) character. The following fragment of PHP 4 code passes, assigns, and returns a variable by reference:


function & addItem( &$item ) {
  $this->items[] = &$item;
  return $item;
}

We tell the function to return by reference by placing an ampersand before the function name. We enforce pass by reference in the method definition by placing the ampersand before the argument variable, and we assign by reference by placing the ampersand after the assignment operator. Failure to do all of these things would result in at least one copy of the Item object being made. PHP 5 would require no ampersands to get the same result.

    [ Team LiB ] Previous Section Next Section