PHP 5: By reference or by value

PHP 4 passed variables by value by default. This was not very pleasant to work with. The way around this was to pepper your code with ampersands (to tell PHP to use references instead) but forgetting to include one was difficult to debug. By default, PHP 5 passes all objects by reference. Therefore calling:

$user->getLogin($_SESSION);
print_r($_SESSION);
class User
{
 function getLogin($sessionArray)
 {
  //Code in here
  $sessionArray[] = “another value”;
 }
}

will result in exactly the same object (the session array) being passed into the method and used by it throughout. As we are adding an extra value to it the session array outside of the method will also change.

N.B. this isn’t particularly good practice in itself as it is not entirely clear from the line User.getLogin($_SESSION); that the $_SESSION array is being changed. A more self-documenting way or writing this would be $_SESSION = User.getLogin($_SESSION); and to return the $sessionArray variable from the getLogin() method.

Next section: Subclasses

Leave a Reply

Your email address will not be published. Required fields are marked *