8.4 Passing Arguments by Reference


You want to force your users to have their arguments passed by reference.

Technique

If you declare that the variable will be passed by reference in the function definition, the variable will always be passed by reference, no matter whether the user passes a reference.

 <?php $tree = new Tree; $tree->depth = 3; generate_tree($tree); function generate_tree(&$tree) {     // Here we generate some data and fill in the tree     // by calling methods on $tree. } ?> 

Comments

References in PHP are somewhat (again, somewhat ) equivalent to the concept of pointers in C. Before I go into the details here, a little disclaimer to appease fellow C programmers: Although the references in PHP are loosely equivalent to pointers in C, there are a couple of major differences. One difference is that in PHP, you never have to dereference your variables as you do in C (via * ). PHP references are more similar to references in C++.

For those unfamiliar with concepts of pointers and references, here is a brief explanation. (For more information, see recipe 4.5.) It all boils down to the fact that every variable has a memory address, sort of like every book in a library has a book number. A reference is the "book number" of the variable. So, instead of passing a copy of a variable to a function, you are really passing only a memory address, which, when dealing with large variables and arrays, is much more memory efficient. Also, passing references enables you to use what are known as destructive functions or functions that modify the variable that is passed to them (as in the example).

PHP 4 is more optimized with regard to value passing. Even if the value is not passed by reference, PHP is smart enough not to pass a copy of the value. Instead, it uses the value from the calling scope and makes a note that this value is being used in one more place. But changing the variable contents in the function will have no effect on the calling scope.

Please note that in the example, we require the arguments to be passed by reference. Although it is possible not to declare the reference in the function but rather pass the variables on a call-by-call basis, doing so constitutes bad programming practice. The person who calls the function should not control what is or is not passed by reference ”that is the duty of the programmer who wrote the function. To that purpose, PHP 4 provides a php.ini directive ( allow_call_time_pass_reference ) that will disallow passing values by reference at call time.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net