Re: call function as variable

From: Date: Sat, 16 Aug 2003 17:16:48 +0000
Subject: Re: call function as variable
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-159801@lists.php.net to get a copy of this message
Tanks a lot! This was exactly that i wanted! Cheers David Otton wrote:
On Sat, 16 Aug 2003 07:58:27 +0200, you wrote:
I have folowing function which they are a member in a class. function foo(){ something } function zoo(){ something else } and i have a array such: $test = array(1=>foo,2=zoo); and i want to call the fuction foo() and zoo something like; $object->$test[1]();
The fact that you say "$object->$test" suggests that foo() and zoo() are methods of a class? The following code snippet contains just about every mechanism for calling a method of a class that there is. The one you'll probably want is call_user_func (array ($C, 'B'), 'call 4'); <? /* Class A has method B */ class A { function B ($s = "None") { echo ("<p>input : $s</p>"); } } /* $C is an instance of A */ $C = new A (); /* $D is an array of strings */ $D = array ('item 1', 'item 2', 'item 3', 'item 4'); /* invoke A::B */ A::B ('call 1'); /* invoke $C->B */ $C->B ('call 2'); /* invoke A::B via call_user_func() */ call_user_func (array ('A', 'B'), 'call 3'); /* invoke $C->B via call_user_func() */ call_user_func (array ($C, 'B'), 'call 4'); /* invoke A::B via call_user_func_array() */ call_user_func_array (array ('A', 'B'), array('call 5')); /* invoke $C->B via call_user_func_array() */ call_user_func_array (array ($C, 'B'), array('call 6')); /* apply A::B to $D via array_walk() */ array_walk ($D, array ('A', 'B')); /* apply $C->B to $D via array_walk() */ array_walk ($D, array ($C, 'B')); ?>


« previous php.general (#159801) next »