Page 1 of 1

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

Posted: Wed Feb 27, 2008 9:11 am
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!

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

Posted: Wed Feb 27, 2008 9:35 am
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);