note 24069 deleted from language.references.pass by sniper
| From: | sniper@php.net | Date: | Tue, 30 Sep 2003 01:24:41 +0000 |
| Subject: | note 24069 deleted from language.references.pass by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-57340@lists.php.net to get a copy of this message | ||
Note Submitter: chris.nospam@chaska.nospam.com
----
Since default argument passing is by COPYING the argument, instead of passing it by reference, it
might seem obvious to some people that passing a class handle or object instance variable would
create a COPY of the entire instance or object. But it was not obvious to me, since most languages
which pass by a method other than by reference, pass by VALUE, and the value of an instance is
almost always a handle pointing to (i.e. a pointer) the object. Thus, calls to class methods which
alter object/class variables will really alter those values in the passed object/class. PHP does
not do this. I spent longer than I care to admit trying to figure out why my class variables were
not retaining the values I was setting them to, only to discover that they were being set in COPIES
which then vanished into thin air. Examples:
// this does not work as expected
class Foo {
var $count = 0;
function add() {
$this->$count++;
}
function show() {
echo "count = " . $this->count . "\n";
}
}
function util( $handle ) {
$handle->add();
$handle->show(); // displays 1
}
$obj = new Foo;
util($obj);
$obj->show(); // displays 0!
Change the util() function defintion to use pass by reference and it works, i.e.:
function util( &$handle ) ...
Hope this helps someone else avoid banging their head for days on a really "simple"
problem. :-)