1

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;
    }
}

2 Answers 2

7

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

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

        $class = new extendclass;
        $class->$mode();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.