如何在PHP中动态调用类方法?类方法不是静态的.看起来
call_user_func(...)
Run Code Online (Sandbox Code Playgroud)
仅适用于静态功能?
谢谢.
Pet*_*ley 92
它适用于两种方式 - 您需要使用正确的语法
// Non static call
call_user_func( array( $obj, 'method' ) );
// Static calls
call_user_func( array( 'ClassName', 'method' ) );
call_user_func( 'ClassName::method' ); // (As of PHP 5.2.3)
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 25
选项1
// invoke an instance method
$instance = new Instance();
$instanceMethod = 'bar';
$instance->$instanceMethod();
// invoke a static method
$class = 'NameOfTheClass';
$staticMethod = 'blah';
$class::$staticMethod();
Run Code Online (Sandbox Code Playgroud)
选项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)
Run Code Online (Sandbox Code Playgroud)
选项1比选项2更快,因此尝试使用它们,除非您不知道要将多少个参数传递给方法.
编辑:以前的编辑器在清理我的答案方面做得很好,但删除了call_user_func_array的提及,这与call_user_func不同.
PHP有
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.call-user-func.php
和
mixed call_user_func_array ( callable $callback , array $param_arr )
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.call-user-func-array.php
使用call_user_func_array比使用上面列出的任一选项慢几个数量级.
Jer*_*ten 16
你的意思是这样的?
<?php
class A {
function test() {
print 'test';
}
}
$function = 'test';
// method 1
A::$function();
// method 2
$a = new A;
$a->$function();
?>
Run Code Online (Sandbox Code Playgroud)
从 PHP7 开始,您使用类似数组的方式:
// Static call only
[TestClass::class, $methodName](...$args);
// Dynamic call, static or non-static doesn't matter
$instance = new TestClass();
[$instance, $methodName](...$args);
Run Code Online (Sandbox Code Playgroud)
只需将类名替换为TestClass,方法名称替换为$methodName,方法参数替换为...$args。请注意,在后一种情况下,该方法是静态还是非静态并不重要。
一个优点是您可以将数组作为可调用函数传递给函数。
PHP 8.1 中有一个新的一流可调用语法:
$callable = TestClass::$methodName(...);
// Or
$callable = $instance->$methodName(...);
$callable(...$args);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57525 次 |
| 最近记录: |