How do I dynamically invoke a class method in PHP?

后端 未结 9 1023
时光取名叫无心
时光取名叫无心 2020-12-08 01:52

How can I dynamically invoke a class method in PHP? The class method is not static. It appears that

call_user_func(...)

only works with st

相关标签:
9条回答
  • 2020-12-08 02:34
    Class Foo{
     public function show(){
      echo 'I am in Foo Class show method';
     }
    
    }
    
    call_user_func(array('Foo', 'show'));
    
    $classname = new Foo;
    call_user_func(array($classname, 'show'));
    call_user_func($classname .'::show'); // As of 5.2.3
    
    $foo = new Foo();    
    call_user_func(array($foo, 'show'));
    
    0 讨论(0)
  • 2020-12-08 02:38

    Option 1

    // invoke an instance method
    $instance = new Instance();
    $instanceMethod = 'bar';
    $instance->$instanceMethod();
    
    // invoke a static method
    $class = 'NameOfTheClass';
    $staticMethod = 'blah';
    $class::$staticMethod();
    

    Option 2

    // invoke an instance method
    $instance = new Instance();
    call_user_func( array( $instance, 'method' ) );
    
    // invoke a static method
    $class = 'NameOfTheClass';
    call_user_func( array( $class, 'nameOfStaticMethod' ) );
    call_user_func( 'NameOfTheClass::nameOfStaticMethod' ); // (As of PHP 5.2.3)
    

    Option 1 is faster than Option 2 so try to use them unless you don't know how many arguments your going to be passing to the method.


    Edit: Previous editor did great job of cleaning up my answer but removed mention of call_user_func_array which is different then call_user_func.

    PHP has

    mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] ) 
    

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

    AND

    mixed call_user_func_array ( callable $callback , array $param_arr )
    

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

    Using call_user_func_array is orders of magnitude slower then using either option listed above.

    0 讨论(0)
  • 2020-12-08 02:44

    THe best way i find is to do

    call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));
    

    It's working like a charm !

    0 讨论(0)
提交回复
热议问题