note 21646 modified in function.call-user-func by danbrown

From: Date: Sat, 19 Jul 2008 21:14:29 +0000
Subject: note 21646 modified in function.call-user-func by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-141748@lists.php.net to get a copy of this message
if you need to get a reference back from a method, you can work around call_user_func()'s shortcomings like this: <?php $globalObj; class tClass { function &instance() { global $globalObj; if(!is_object($globalObj)) { $globalObj = new tClass(); } return $globalObj; } } $classname = "tClass"; # calling the function this way won't # return a reference. $test = &call_user_func(array($classname,"instance")); # but if we call it again with the instance # that we just got, it'll be the right # one $test = &$test->instance(); # so test is now a reference to $globalObj, just like it should be # let's verify it: $test->blah=1; echo "<pre>"; print_r($test)."\n"; print_r($globalObj); echo "</pre>"; # there, now it behaves just like you'd expect ?> --was-- if you need to get a reference back from a method, you can work around call_user_func()'s shortcomings like this: <? $globalObj; class tClass { function &instance() { global $globalObj; if(!is_object($globalObj)) { $globalObj = new tClass(); } return $globalObj; } } $classname = "tClass"; # calling the function this way won't # return a reference. $test = &call_user_func(array($classname,"instance")); # but if we call it again with the instance # that we just got, it'll be the right # one $test = &$test->instance(); # so test is now a reference to $globalObj, just like it should be # let's verify it: $test->blah=1; echo "<pre>"; print_r($test)."\n"; print_r($globalObj); echo "</pre>"; # there, now it behaves just like you'd expect ?> http://php.net/manual/en/function.call-user-func.php

« previous php.notes (#141748) next »