PHP includes class functions with variables

I am trying to use a variable to get a function in an extended class, this is what I want to do, but I cannot get it to work, thanks for your help.

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

        $class = new extendclass;
        $class->$mode;
    }
}

      

+1


a source to share


2 answers


Do not include parentheses "()" in the $ mode variable.



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

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

      

+7


a source


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

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

      

Regular functions (not a method) and static methods are stored as simple 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 permissive parameters are passed to the callback function:

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

      

This might seem like an unnecessary complication, but in many cases you might want to programmatically construct a function call, or you might not know in advance how many parameters you will pass to the function (some functions, such as array_merge and sprintf, allow a variable number of parameters).

0


a source







All Articles