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 ...

Get PHP 5 Power Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.