Resources are passed by reference
When copying one resource to another, you're actually creating a reference to the original resource, this is not an actual copy.
This is illustrated by the following example:
echo '<pre>'; // create an image resource $image = imagecreate(100, 100); // print the resource var_dump($image); // the above prints "resource(30) of type (gd)" // create a copy // (actually creating a reference, // although =& is not implicitly used) $copy = $image; // print the reference var_dump($copy); // the above prints "resource(30) of type (gd)", same as before // destroy the image resource imagedestroy($image); // this prints "resource(30) of type (Unknown)" // so the image was destroyed var_dump($image); // this also prints "resource(30) of type (Unknown)" // meaning that the reference points to a destroyed image var_dump($copy); echo '</pre>';
This entry was posted on Wednesday, September 7th, 2005 and is filed under PHP certification. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

September 15th, 2005 at 2:52 am
under PHP 5.0 and above !
October 2nd, 2005 at 5:07 pm
@Constantine, under PHP5, EVERYTHING is passed by reference unless we explicitly clone something. The great big change we’ve all been waiting for. I in fact refuse to take the Zend exam until it’s PHP5ied because right now it would confuse the hell out of me.
In PHP4, which Stoyan is referring to, a RESOURCE is passed by reference while anything else is passed by value. Try replacing the imagecreate line by $image = “foo”; and the imagedestroy line by unset($image); The copy will still result in a string in the var_dum($copy); line, indicating pass by value.
October 9th, 2005 at 10:48 pm
That’s right, thanks Marco. I had PHP4 in mind.