Section 13.3. Passing Objects to Functions


13.3. Passing Objects to Functions

As previously mentioned, one of the larger changes in PHP 5 is that if you pass objects to a function, they are no longer copied. Although this is usually what you want, it might be that you actually relied on your object being copied. If that's the case, your script will no longer work correctly. Look at this example:

 <?php       class str {             var $string;             function str($string) {                   $this->string = $string;             }       }       function display_quoted($string)       {             $string->string = addslashes($string->string);             echo $string->string;       }       $s = new str("Montreal's Finest Bagels\n");       display_quoted($s);       echo $s->string; ?> 

Because in PHP 4, passing the $s object to the function creates a copy of the object, the output in PHP 4 is

 Montreal\'s Finest Bagels Montreal's Finest Bagels 

In PHP 5, the object's handle is passed and the object is actually modified. Thus, PHP 5 produces different output:

 Montreal\'s Finest Bagels Montreal\'s Finest Bagels 

If you want to modify only a copy in PHP 5, one solution is to copy (clone) the object yourself when you pass it to the function. Do this by using the clone operator:

 display_quoted(clone $s); 

Another solution is to disable the new behavior by setting the php.ini option zend.ze1_compatibility_mode to 1. Or, you can set this option inside your script itself, but you need to set it before passing the object to a function.

Tip

If your script that relies on the pass-by-copy behavior needs to work with both PHP 4 and PHP 5, using the clone operator won't work, because this operator does not exist in PHP 4. The clone operation will throw an E_ERROR error when run in PHP 4. In this case, it's better to use the compatibility mode setting.




    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net