Search code examples
phpsyntaxstatic-functions

reference to static function in PHP


is possible get reference to static function and run? like this:

namespace vendor\foo;

class Bar
{
    public static function f1()
    {
        echo 'f1';
    }
    public static function f2($id)
    {
        echo 'f2: '.$id;
    }

}

and

$fs = array(
    'f1'=>\vendor\foo\Bar::f1,
    'f2'=>\vendor\foo\Bar::f2
);

$fs['f1']();
$fs['f2']('some id');

or the only way is call_user_func ?

note: php 5.3


Solution

  • You have multiple options to do this

    1. using a string variable for the class name and the method name
    2. using callbacks together with call_user_func()
    3. using Reflection

    The following examples shall demonstrate these options:

    <?php
    
    namespace vendor\foo;
    
    class Bar {
    
        public static function foo($arg) {
            return 'foo ' . $arg;
        }   
    }
    

    Option 1 : Using a string variable for the classname and the method name:

    /* prepare class name and method name as string */
    $class = '\vendor\foo\Bar';
    $method = 'foo';
    // call the method
    echo $class::$method('test'), PHP_EOL;
    // output : foo test
    

    Option 2 : Perpare a callback variable and pass it to call_user_func() :

    /* use a callback to call the method */
    $method = array (
        '\vendor\foo\Bar', // using a classname (string) will tell call_user_func()
                           // to call the method statically
        'foo'
    );
    
    // call the method with call_user_func()
    echo call_user_func($method, 'test'), PHP_EOL;
    // output : foo test
    

    Option 3 : Use ReflectionMethod::invoke() :

    /* using reflection to call the method */
    $method = new \ReflectionMethod('\vendor\foo\Bar', 'foo');
    
    // Note `NULL` as the first param to `ReflectionMethod::invoke` for a static call.
    echo $method->invoke(NULL, 'test'), PHP_EOL;
    // output : foo test