|
|
 |
call_user_func (PHP 3 >= 3.0.3, PHP 4, PHP 5) call_user_func --
Call a user function given by the first parameter
Descriptionmixed call_user_func ( callback function [, mixed parameter [, mixed ...]] )
Call a user defined function given by the
function parameter. Take the
following:
Object methods may also be invoked statically using this function
by passing array($objectname, $methodname) to
the function parameter.
Note:
Note that the parameters for call_user_func() are not
passed by reference.
See also:
is_callable(),
call_user_func_array(),
and information about the callback type.
User Contributed Notes
call_user_func
info at webseiteselberpflegen dot de
18-May-2005 03:00
It seems like call_user_func() can not be used to create Objects via the new Command.
The Following example dosen't work:
<?
include_once(class_".$type.".php");
$object = new call_user_func ('bdv_'.$type);
?>
But this works:
<?
include_once(class_".$type.".php");
$constr = 'bdv_'.$type;
$object = new $constr();
?>
d at safetypub dot org
15-Mar-2005 10:43
callbacks, this par excellence, goes with set error handler, everywhere you'ren't sure of extensio de intensionibus (animis alii).
<?php
$checkMe = null;
$detail = array();
set_error_handler("imErrant");
array_shift($argv);
if ($argc == 1){
call_user_func(strtolower($argv[0]));
} else if($argc == 2){
call_user_func(strtolower($argv[0]), $argv[1]);
}
else
call_user_func_array(strtolower($argv[0]),array_shift($argv));
if($checkMe)var_export($detail);
function imErrant($no, $str, $file, $line)
{
global $checkMe, $detail;
$checkMe = $no;
$detail = array($str, $file, $line);
}
?>
24-Feb-2005 09:46
<?php
class Duke
{
var $m_pRaiser;
var $m_strRaiserFun;
var $m_objArgs;
function Duke( $pRaiser,
$strRaiserFun,
$objArgs )
{
$this ->m_pRaiser = $pRaiser;
$this ->m_strRaiserFun = $strRaiserFun;
$this ->m_objArgs = $objArgs;
}}class A
{
function OnEventHandler( $sender, $args ){
$sender ->SayHello();
}function OnEvent( $pDuke = null )
{
if( $pDuke == null )
{
call_user_func( array( &$this, "OnEventHandler" ), $this, null );
return;
}
call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );
}function SayHello(){
echo "A::SayHello" . "<br>";
}}class B extends A
{
function SayHello(){
echo "B::SayHello" . "<br>";
}}$a = &new A();
$b = &new B();
$pDuke = &new Duke( $b, "OnEventHandler", null );
$b ->OnEvent();
$b ->OnEvent( $pDuke );
?>
zxy at estec-jp dot com
24-Feb-2005 04:57
A simple event handler dispose released by useful callback in PHP 4.x
<?php
class Duke
{
var $m_pRaiser;
var $m_strRaiserFun;
var $m_objArgs;
function Duke( $pRaiser,
$strRaiserFun,
$objArgs )
{
$this ->m_pRaiser = $pRaiser;
$this ->m_strRaiserFun = $strRaiserFun;
$this ->m_objArgs = $objArgs;
}}class A
{
function OnEventHandler( $sender, $args ){
$sender ->SayHello();
}function OnEvent( $pDuke )
{
call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );
}function SayHello(){
echo "A::SayHello" . "<br>";
}}class B extends A
{
function SayHello(){
echo "B::SayHello" . "<br>";
}}$a = &new A();
$b = &new B();
$pDuke = &new Duke( $b, "SayHello", null );
$b ->OnEvent( $pDuke );
?>
rob at PLEASEDONT dot digital-crocus dot SPAMME dot com
18-Feb-2005 08:16
Hey
I'm struggling to think of a practical use for this function that can't be duplicated with variable functions. The only use I can think of is when calling variable functions when your variable need modification:
<?php
function hey1 { echo "hey1"; }
function hey2 { echo "hey2"; }
function hey3 { echo "hey3"; }
for ($n = 1; $n <= 3; $n++) {
$func = "hey$n";
$$func();
call_user_func("hey$n");
}
?>
call_user_func() is one less line, however I would always use variable variables for readability. Are there any more practical uses I'm overlooking?
bostjan dot skufca at domenca dot com
15-Dec-2004 02:33
This is the CORRECTED VERSION of previous note. After playing a while I realised that objects are not passed by reference implicitly, you have to do it on your own, so:
call_user_func(array($objectBar, 'methodFoo')); // case sensitive
first duplicates object $objectBar (internally) and only then calls it's methodFoo. This kind of use is discouraged as it may result in "unpredicted behaviour".
Correct version is here.
call_user_func(array(&$objectBar, 'methodFoo')); // case sensitive
(note the reference operator).
--- and the corrected note is here ---
I couldn't find any simple list of available callback variations, so I made one. It is tested on PHP 4.3.9 only.
If you need to call ordinary function:
call_user_func('funcFoo');
If you need to call CLASS method (NOT object):
call_user_func(array('classBar', 'methodFoo')); // case insensitive
If you need to call OBJECT method:
call_user_func(array(&$objectBar, 'methodFoo')); // case sensitive
If you need to call method of object of object:
call_user_func(array(&$objectBar->objectTor, 'methodFoo')); // case sensitive
If you need to call object method from within the very same object (NOT CLASS!):
call_user_func(array(&$this, 'methodFoo'));
07-Oct-2004 02:23
If you are trying to instantiate an object from a class whose name is dynamic, you WILL NOT be able to do this with call_user_func() and I do not suggest that you do it with eval(). The way to do it is actually much simpler than i thought. As far as i know this works in PHP 4 and 5:
<?PHP
class foo {
var $boo;
function foo( $someVal ) {
$this->boo = $someVal;
}
}
$ClassToUse = "foo";
$bar = new $ClassToUse('test');
echo $bar->boo;
?>
arjini at mac dot com
29-Mar-2004 07:04
Some of the wierder examples below confused me, and made me think that the following would work (but it does!).
<?
class barber{
function shop($one,$two,$three,$four='quartet'){
echo $one.','.$two.','.$three.','.$four;
}
}
$bsq = new barber;
call_user_func(array(&$bsq,'shop'),'one','two','three');
class bigBarber{
var $quartet;
function bigBarber(){
$this->quartet = 'four';
}
function shop($one,$two,$three,$five='quintet'){
echo $one.','.$two.','.$three.','.$this->quartet.','.$five;
}
}
$bbsq = new bigBarber();
call_user_func(array(&$bbsq,'shop'),'one','two','three');
?>
Kris Koskelin
22-Jan-2004 05:21
I was trying to use this function to call a method of an already-instantiated object. I needed to do this with the object itself, not simply call the class' method.
To accomplish this, I really avoided this particular function altogether like this:
<?
if ( method_exists($my_obj, $action) ){
return $my_obj->{$action}();
}
?>
I hope someone else finds this useful. Note that doing this allows you to pass params to the function more-or-less in the same way you would to any other class method.
Michele.Manzato at verona.miz.it
29-Sep-2003 10:49
With overload()ed classes call_user_func_* calls real class methods only. If the method does not exist then PHP does not try with the "__call()" magic method (at least until PHP 4.3.3). See this:
<?php
class A
{
function A() {}
function __call($method, $args, &$ret) {
echo "__call(): You called '{$method}()'<br>\n";
return true;
}
function regular() {
echo "You called 'regular()'<br>\n";
}
};
overload("A");
$a = new A;
$a->regular(); call_user_func(array(&$a, "regular")); $a->hello(); call_user_func(array(&$a, "hello")); ?>
Carl
28-Jul-2003 01:53
I had a problem where I wanted to parameterize a callback. The end called was in an external class, but I needed to save some state for the callback that didn't make sense to keep in the original object, as it might change from call to call...
<?php
class foo
{
function foo()
{
$str = "Hello There";
$str2 = "Carl";
$that =& new holder($str);
call_user_func(array(&$that, 'callback'), $str2);
}
}
class holder
{
function holder($aParam)
{
$this->param = $aParam;
}
function callback($aStr)
{
echo "A=$this->param, B=$aStr\n";
}
}
?>
matt at tasonline dot com
23-Nov-2002 02:24
On PHP 4.2.3 (not sure about older releases) you can send objects by reference by sending the reference from call_user_func()
<?php
function myFunction(@$obj)
{
$obj->doThis('hello');
return 0;
}
$myObj = new CObject();
call_user_func('myFunction', @$myObj);
?>
phil at gettcomm dot com
21-May-2002 09:51
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";
$test = &call_user_func(array($classname,"instance"));
$test = &$test->instance();
$test->blah=1;
echo "<pre>";
print_r($test)."\n";
print_r($globalObj);
echo "</pre>";
?>
teleware at mind dot net
08-Apr-2002 03:34
I ran into some quirky behavior using call_user_func with an object. The function parseAction() below lets me call any of my object's methods by passing the name of the method into a page (e.g. http://xyz.com/page.php?action=login).
<?php
class MyClass {
function parseAction($actionKey)
{
global $METarget;
if(method_exists($this,$actionKey))
{
call_user_func(array(&$this,$actionKey));
return;
}
else
{
exit("Unknown action keyword: $actionKey");
}
}
...
...
}
?>
I found that my member variables weren't always being updated correctly. The numberic values were preserved but the string variables retained their old value. The solution was to put the reference operator '&' in front of the object's variable. In this case it's $this because I'm calling it from within the object but this was also true when calling parseAction from an instanciated object e.g. call_user_func(array(&$myObject,$actionKey))
dougqh at hotmail dot com
07-Mar-2002 07:16
The previous note I posted had an error in the source code. That has been corrected in this note.
Note, that returning by reference does not work properly when the function
is called using call_user_func.
This example illustrates the problem...
$globalVar = 0;
function &staticFunction()
{
global $globalVar;
return $globalVar;
}
$result =& call_user_func( "staticFunction" );
$result = 3;
print "result:" . $result . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";
$result2 =& staticFunction();
$result2 = 3;
print "result2: " . $result2 . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";
The above code results in the following output ...
Note that $result is not a reference to $globalVar.
result:0
globalVar: 0
result2: 3
globalVar: 3
Also, the use of call_user_method is now deprecated in favor of passing
array( &$object, $method ) as the function to call_user_func. This is
reported when error reporting is set to E_ALL in the latest versions of
PHP.
danyloco at yahoo dot com
17-Jul-2001 06:31
I was trying to call multiple functions within a class, and after a brain frying experience this is what came out... hope it helps:
<?php
class Foo {
function hey1($id){echo "In hey1";}
function hey2($id){echo "In hey2";}
function runtest($id) {
for($i=1; $i<=2; $i++) {
$fp = "hey".$i;
$this->$fp($id);
}
}
}
?>
It worked like a charm :).
dayiogluNOSPAM at metu dot edu dot tr dot NOSPAM
12-Mar-2001 05:03
Happily call_user_func can now call
methods of some existing objects; added
to the CVS Fri Mar 9 18:09:26 2001 EDT.
Below is an example:
<?php
class provider {
function myfunction($x) {
echo "burak was at $x\n";
}
}
class dispatcher {
function process($p2,$p3) {
call_user_func($p2, $p3);
}
}
function independent()
{
echo "just a test";
}
$x= new provider();
$y= new dispatcher();
$y->process(array($x,'myfunction'),"conference");
$y->process(independent,"");
?>
ceco at noxis dot net
28-Nov-2000 11:01
I find it easier in a lot of cases to use something like that
<?
function test($p1){
echo $p1."<br>";
return $p1/2; }
$func = "test";
echo $func(6);
?>
tetherow at nol dot org
29-Aug-2000 03:39
Trying to call a class method with call_user_function? call_user_method doesn't really work since you need an object to pass to the call. You can get around it by creating a 'place holder' instance and call_user_method.
andreyhristov at yahoo dot com
22-Aug-2000 08:09
Let say we construct somehow the name of the function. In some cases we can use nested 'switch' but the alternative is to to use for and parse a string to construct the function name, after than we also can construct and the
parameter(s) for it. It is like using of eval. I use it in one of my projects to construct a name of nested array like
$ar['1999'['july']['29']['19'] , etc. the problem is in that I'm parsing a string to construct the name. If I've {1:2:3} the array name will be $ar['1']['2']['3'] but if i've
{1:2:3:4:5} it will be $ar['1']['2']['3']['4']['5']. Eval is the only way (very hard because of characters escaping is needed) to do it. So this function is of the type of EVAL().
USE IT wherever your script is 'self-modified';
| |