Dynamically Named Static Method Calls

Something that is being added in PHP 5.3.0 but is sorely missed in current versions is the ability to call a static class method from variables, for example:

$class = 'classname';
$method = 'methodname';
$vars = 'whatever';

// Only possible in PHP 5.3.0 and above
$output = $class::$method($vars);

It is something that is occasionally very useful (e.g. you have a validation class triggering other regional classes) and is already possible with standard class calls. Thankfully it’s very easy to simulate with eval:

function static_call($class, $method, $arguments = '')
{
    if(is_array($arguments))
    {
        $arg_string = '';
        $count      = 0;

        foreach($arguments as $key => $value)
        {
            if($count > 0)
            {
                $arg_string .= ', ';
            }

            $arg_string .= '$arguments['.$key.']';

            $count++;
        }
    }
    else
    {
        $arg_string = '$arguments';
    }

    eval('$return = '.$class.'::'.$method.'('.$arg_string.');');

    return $return;
}

Using it is very simple:

$class = 'classname';
$method = 'methodname';
$vars = 'whatever';

$output = static_call($class, $method, $vars);

And will handle a single variable or an array of the required variables in order. There’s not much else to say apart from use it wisely!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>