php - 如何在 PHP 中动态调用类方法?

php - 如何在 PHP 中动态调用类方法?

选项1

// invoke an instance method

$instance = new Instance();

$instanceMethod = 'bar';

$instance->$instanceMethod();

// invoke a static method

$class = 'NameOfTheClass';

$staticMethod = 'blah';

$class::$staticMethod();

选项 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)

选项 1 比选项 2 快,因此请尝试使用它们,除非您不知道要传递给该方法的参数数量。

编辑:以前的编辑器在清理我的答案方面做得很好,但删除了与 call_user_func 不同的 call_user_func_array 的提及。

PHP有

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

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

mixed call_user_func_array ( callable $callback , array $param_arr )

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

使用 call_user_func_array 比使用上面列出的任一选项慢几个数量级。

相关推荐

楚楚街如何退款
365下载bet

楚楚街如何退款

🕒 06-27 👁️ 9782
古筝筝码的摆放
365下载bet

古筝筝码的摆放

🕒 06-29 👁️ 7543