views:

824

answers:

2

I am trying to use a variable to get a function in a extended class, this is what I want to do but I can't get it to work, Thanks for your help.

class topclass {
    function mode() {
        $mode = 'function()';

        $class = new extendclass;
        $class->$mode;
    }
}
+6  A: 

Don't include the brackets "()" in the $mode variable.

class topclass {
    function mode() {
        $mode = 'functionx';

        $class = new extendclass;
        $class->$mode();
    }
}
BlaM
A: 

You can also use a callback, which is an array tuple of the instance and a string naming the function. If the intended call is $foo->bar(), then the callback would be:

$callback = array($foo, 'bar');

Regular functions (not a method) and static methods are stored as plain strings:

// Function bar
$callback = 'bar';
// Static method 'bar' in class Foo
$callback = 'Foo::bar';

It is called with call_user_func or call_user_func_array, the second allowing parameters to be passed to the callback function:

// No parameters
call_user_func($callback);
// Parameters 'baz' and 'bat'
call_user_func_array($callback, array('baz', 'bat');

It may seem like this is unnecessary complication, but in many instances, you may want to be able to programmatically build a function call, or you may not know ahead of time how many parameters you will be passing to a function (some functions, such as array_merge and sprintf allow a variable number of parameters).

Jeff Ober