Re: function by reference

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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) {
    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
?>


It's going to hurt thinking about that.  :-)

References (and pointers in lower level languages) can be painful :(

It's quite useful with objects.

function &getdb() {
  if (!isset($GLOBALS['DBClass'])) {
    $dbclass = &new DBClass();
.....
    $GLOBALS['DBClass'] = &$dbclass;
  }
   return &$GLOBALS['DBClass'];
}

So in this case, every time you call 'getdb', you don't want it to start a new object and return that (memory usage because it has to set up the object again, you have to reconnect to the db and so on).

You want it to use the same object over and over again.

So you return by reference.


You also have to call by reference:

$my_db = &getdb();

rather than:

$my_db = getdb();

otherwise it returns a copy rather than a reference.

--
Postgresql & php tutorials
http://www.designmagick.com/

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux