3

I have a class Sections:

class Sections {
    public static function get($name) {
        //
    }
}

And I would like to call the static function get() from it with a variable (http://php.net/manual/en/functions.variable-functions.php):

$section = 'Sections::get';
$section('body');

But it gives me a Fatal error: Call to undefined function Sections::get()

Is it possible to call a static function in this way?

Thanks!

3 Answers 3

4

You need to store the class separately from the method:

$class = 'Sections';
$method = 'get';

Now you can call it like this:

$class::$method('body');
Sign up to request clarification or add additional context in comments.

Comments

0

Try using call_user_func to do this:

$section = array('Sections', 'get');
call_user_func($section, 'body');

Or:

$section = 'Sections::get';
call_user_func($section, 'body');

1 Comment

A problem that I see with your solution is that in stacktraces you'll only see call_user_func() but not Sections::get() which makes the trace less worth for debugging. That's why I try to avoid call_user_func() whenever possible.
0

I've solved it with the help of a function outside of the class:

class Sections {
    public static function get($name) {
        //
    }
}

function section($name) {
    Sections::get($name);
}

Now I can do:

$section = 'section';
$section('body');

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.