Re: function by reference
| From: | Martin Alterisio \"El Hombre Gris\" | Date: | Wed, 12 Apr 2006 03:15:13 +0000 |
| Subject: | Re: function by reference | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-233823@lists.php.net to get a copy of this message | ||
Well, it was a bad example to begin with, first of all max() is already defined in php, I should at least checked that before posting. Second, I forgot PHP (the Zend engine) has an interesting way of handling variables, when you copy assign a var or pass it as an argument of a function, a real copy is not made but a reference. When you modify the reference, an actual copy is made before the modification. What's happening with the function you posted is that the variables are not passed by copy but by reference, that's why it works. Anyway, this is due to conditions on the way PHP (the Zend engine) handles its internal, you shouldn't rely on this in your code.
http://www.zend.com/zend/art/ref-count.php
tedd wrote:
The ampersand before the function name indicates that the function returns a reference instead of a copy of the variable, for example: <?php function &max(&$var1, &$var2) {It's going to hurt thinking about that. :-) But that produces the same results as: <?php function max($var1, $var2) {if ($var1 > $var2) return $var1; else return $var2;} $global1 = 10; $global2 = 9; $maxglobal =& max($global1, $global2); $maxglobal++; echo $global1; //this will print 11 since $maxglobal is a reference to $global1 ?>if ($var1 > $var2) return $var1; else return $var2;} $global1 = 10; $global2 = 9; $maxglobal =& max($global1, $global2); $maxglobal++; echo $global1; //this will print 11 since $maxglobal is a reference to $global1 ?> Note the absence ampersands in the function, but an ampersand remains in the assignment: Thanks. tedd