Proper Use of References in PHP

Posted by Jetlogs @ 6:40 pm
Category: PHP, Web Development

It has been a long time since I’ve made an article about programming, so its finally time I stop slacking and write an article. For today’s article, I’m going to talk about the proper use of references in PHP.

It has been hard-wired to almost every PHP programmer, that when passing arrays or objects to functions, they must be passed by reference, not by value so that the function will not work on the copy, hence improving performance.

Here is the sample code in PHP 4 that most programmers have been taught with regards to references


function foo(&$variable_array)
{
     shuffle($variable_array);
     return $variable_array;
}

$bar = array(1, 2, 3, 4, 5);
foo($bar); //returns a shuffled array

It sounds logical to always use references when passing large and complex variables such as arrays and objects. In this sample code, if we were to pass the array by value, PHP will automatically create a copy of the variable since we modified its contents. However this isn’t usually the case. Take a look at this scenario:


function foo(&$variable_array)
{
     echo $variable_array[0];
}

$bar = array(1, 2, 3, 4, 5);
foo($bar); //prints 1

In this code, we didn’t modify the array’s value at all. If we were to just pass the array by value, PHP will not make a copy of the array since we didn’t have any changes to the variable itself. So instead of speeding up performance, we added an unnecessary step of adding a reference to a variable.

To put is shortly, references should only be used when the variables passed are complex like arrays, objects, and resources and only if the variable is going to me modified inside the function. Otherwise, just use the regular pass by value method.

It is a good thing that thinking about when to use references was significantly made easier in PHP 5, where everything is passed by reference by default.


1 Comment »

1 Comment to “Proper Use of References in PHP”

  1. Pingback:
    1
    Jetlogs.org » Syntax Highlightling with Chili

    [...] Proper Use of References in PHP [...]

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License