PHP References

References in PHP are a way to access the content in a variable by different names. They are not at all like pointers in C. For instance, you cannot perform pointer arithmetic using them and they are not actual memory addresses.

I’ve found that references in PHP are fairly rare, but in the few cases I’ve seen them in the wild, I’ve always assumed that they were used for their faster performance but it turns out that by-reference activity is often slower than its by-value counterpart, because PHP uses a clever “deferred-copy” mechanism that actually optimizes by-value assignments.

Here is a simple php reference example:

  1.  
  2. $a = 10;
  3. $b = &$a; // by reference
  4. $b = 20;
  5. echo $a; // Outputs 20
  6.  

However PHP references are useful when used as a return value for a function. If they are used on something like
a database resource then you probably don’t want to be returning a copy:

  1.  
  2. function &query($sql)
  3. {
  4.         $result = mysql_query($sql);
  5.         return $result;
  6. }
  7.  

References can also be useful as a function parameter to pass by reference instead of by copy. So any changes that are made to the parameter survive the function.

One thing to watch out for when using references in a foreach loop is to make sure that you unset the reference. Otherwise you may inadvertently overwrite the last entry in the array.

  1.  
  2. foreach($data_array as &$value)
  3. {
  4.         do_something_with_value();
  5. }
  6. unset($value);
  7.  

I definitely expext at least a few questions to touch on references on the Zend PHP Certification Exam.

Leave a Reply

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

*