On Sat, 2009-05-02 at 01:07 -0400, Paul M Foster wrote: > In another thread (which I mercifully declined to highjack), someone > cited: > > > Taken from http://www.corephp.co.uk/archives/19-Prepare-for-PHP-6.html > > And I read this: > > Both '$foo =& new StdClass()' and 'function &foo' will now raise an > E_STRICT error. > > I don't use this much, but where I do, it's vital. Typically, I use it > to ensure a single copy of the $config for an application, as: > > function &get_config() ... > > and/or: > > $cfg =& get_config(); > > If this is going away, how do you return things by reference, so as to > ensure a single copy of something (yes, I know the singleton pattern can > be used; I do use it as well; it's more complicated)?
PHP5 made it so that objects are always passed by handle. When assigned or passed as a parameter a copy of the object handle is passed (rather than a copy of the object itself a la PHP4). Given this, you are in many ways passing around an implicit reference. It's not exactly a reference, since there are subtle differences, but the object won't be cloned as it is in PHP4 using this method. So singletons will work as expected. For example: <?php $a = new StdClass(); $a->a = 'a'; $b = new StdClass(); $b->b = 'b'; $c = new StdClass(); $c->c = 'c'; $d = new StdClass(); $d->d = 'd'; $x = $a; $x->x1 = 'x1'; $x = $b; $x->x2 = 'x2'; $y = &$c; $y->y1 = 'y1'; $y = $d; $y->y2 = 'y2'; echo "a:\n"; print_r( $a ); echo "b:\n"; print_r( $b ); echo "c:\n"; print_r( $c ); echo "d:\n"; print_r( $d ); echo "x:\n"; print_r( $x ); echo "y:\n"; print_r( $y ); ?> You will get the following output in PHP5: a: stdClass Object ( [a] => a [x1] => x1 ) b: stdClass Object ( [b] => b [x2] => x2 ) c: stdClass Object ( [d] => d [y2] => y2 ) d: stdClass Object ( [d] => d [y2] => y2 ) x: stdClass Object ( [b] => b [x2] => x2 ) y: stdClass Object ( [d] => d [y2] => y2 ) The difference between references and handles in PHP5 is exemplified by the output of $a versus the output of $c. In the case of $c because we assign a reference for $c to $y, then subsequently we assign $d by value, we essentially completely replace the object $c with $d. Whereas when we assigned $a by value to $x, then subsequently assigned $b by value to $x only the handle value was changed. Cheers, Rob. -- http://www.interjinn.com Application and Templating Framework for PHP -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php