ComputerUser
ComputerUser

Reputation: 4878

Dynamically call a static function?

Could someone fill in the blank. I need to call a static function on a class. Do I need to use eval here?

// Some settings require function calls
$switch = array ('random_image' => 'Splashpage::get_random_image()', 'splash_photos_count' => 'Splashpage::count_splash_photos()');
foreach($switch as $key => $function) {
    if ($name == $key) {
        return ... $function
    }
}

Upvotes: 1

Views: 2221

Answers (4)

BoltClock
BoltClock

Reputation: 723498

If you have PHP 5.2.3 or later, call_user_func() will work with static methods passed in that format:

foreach($switch as $key => $function) {
    if ($name == $key) {
        return call_user_func($function);
    }
}

Also, if you're going to return the result of the method call right away, you should not need a loop since that if condition will only get one chance to evaluate on true:

if (isset($switch[$name]) && is_callable($switch[$name])) {
    return call_user_func($switch[$name]);
}

Upvotes: 2

ComputerUser
ComputerUser

Reputation: 4878

Everyone has been partly right.

Firstly this array is wrong.

$switch = array ('random_image' => 'Splashpage::get_random_image()', 'splash_photos_count' => 'Splashpage::count_splash_photos()');

It should be:

$switch = array ('random_image' => 'Splashpage::get_random_image', 'splash_photos_count' => 'Splashpage::count_splash_photos');

This allows you to call - as 2 people have said - call_user_func and bobs your uncle.

$switch = array ('random_image' => 'Splashpage::get_random_image', 'splash_photos_count' => 'Splashpage::count_splash_photos');
if(isset($switch[$name])) {
    return call_user_func($switch[$name]);
}

Upvotes: 1

Jan Hančič
Jan Hančič

Reputation: 53931

If you will always call those methods on the same class you could only put method names in your array and then call them like this:

$switch = array ('random_image' => 'get_random_image', 'splash_photos_count' => 'count_splash_photos');
foreach($switch as $key => $function) {
    if ($name == $key) {
        return Splashpage::$function ();
    }
}

Upvotes: 1

Thariama
Thariama

Reputation: 50832

Use the call_user_func function:

http://php.net/manual/en/function.call-user-func.php

Example:

call_user_func('myClassName::'.$function);

Upvotes: 1

Related Questions