note 24069 added to language.references.pass

From: Date: Mon, 05 Aug 2002 21:46:12 +0000
Subject: note 24069 added to language.references.pass
Groups: php.notes 
Request: Send a blank email to php-notes+get-34340@lists.php.net to get a copy of this message
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() { $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. :-) -- http://www.php.net/manual/en/language.references.pass.php http://master.php.net/manage/user-notes.php?action=edit+24069 http://master.php.net/manage/user-notes.php?action=delete+24069 http://master.php.net/manage/user-notes.php?action=reject+24069

« previous php.notes (#34340) next »