Storing name of a member function of a class in a string

Ye' old general discussion board. Basically, for everything that isn't covered elsewhere. Come here to shoot the breeze, shoot your mouth off, or whatever suits your fancy.
This forum is not for asking programming related questions.

Moderator: General Moderators

Post Reply
LonelyProgrammer
Forum Contributor
Posts: 108
Joined: Sun Oct 12, 2003 7:10 am

Storing name of a member function of a class in a string

Post by LonelyProgrammer »

Is there anyway to get this to work?

Code: Select all

 
 
class cApplication
{   
    
    function __construct($initTask)
    {
        // debug
        echo "<pre>";
        print_r($initTask);
        echo "</pre>";
        
        foreach($initTask as $initFunction)
            $initFunction();
    }
}
 
// Testing Class
class test_application_framework
{
    function test_init()
    {   
        $initTask[] = 'test_application_framework::setup1';
        $initTask[] = 'setup2';
        
        $app = new cApplication($initTask);     
        
    }
    
    function setup1()
    {
        echo "From inside test_application_framework<br>";
    }
}
 
function setup2()
{
    echo "from setup2<br>";
}
 
 
The global function setup2 can be invoked by storing its name inside the array. But how do I do the same for the member function setup1?

Any help will be appreciated!
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: Storing name of a member function of a class in a string

Post by EverLearning »

When you're calling a method of a class you cant just call it with $variable() syntax. You have to use call_user_func_array or use PHP5 Reflection functionality

So you need to substitute the

Code: Select all

$initTask[] = 'test_application_framework::setup1';
with

Code: Select all

$initTask[] = array('test_application_framework', 'setup1');
and then invoking the method:

Code: Select all

$initFunction();
with

Code: Select all

call_user_func_array($initFunction, null);
Post Reply