accessing class method from variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
kendall
Forum Regular
Posts: 852
Joined: Tue Jul 30, 2002 10:21 am
Location: Trinidad, West Indies
Contact:

accessing class method from variable

Post by kendall »

Hi,

How can I execute the method of a class that is passed via a variable?

e.g.

Code: Select all

 
// class
class M {
function send(){
}
}
 
$class_method = 'send'; // the method of class M
 
$test = new M();
 
thus the accessing of it will be

Code: Select all

 
$test->{$class_method}() 
 
or

Code: Select all

$test->{$class_method. '()'}
:?: :?: :?: :?: :?: :?: :?: :?:
ahowell
Forum Newbie
Posts: 17
Joined: Mon Sep 01, 2008 9:18 pm

Re: accessing class method from variable

Post by ahowell »

Code: Select all

class foo
{
    
    public function bar()
    {
        echo 'bar';
    }
    
}
 
 
$foo = new foo();
 
$method = 'bar';
 
$foo->$method();
Post Reply