PHP回调:类的方法是否具有:: class的等效项? [英] PHP callback: Is there an equivalent for ::class for a method of a class?
问题描述
在PHP中,可以通过这样的类名称解析获得完整的类名称:
In PHP it is possible to get a full class name via class name resolution like this:
示例:
namespace Name\Space;
class ClassName {}
echo ClassName::class;
输出: Name \ Space \ ClassName
这比直接在代码中使用字符串 Name \ Space \ ClassName
更好,因为代码自省(尤其是在IDE中)可以直接找到错误.
This is better than using the string Name\Space\ClassName
directly in the code because code introspection especially in IDEs can find an error directly.
我想知道类的方法是否有类似的东西-这对回调函数特别有用.
I wonder if there is something similar for methods of a class - this would be specifically useful for callback functions.
这基本上就是传递回调的方法:
This is how you can basically can pass a callback:
$a = function($callback,$arg) { return $callback($arg); }
$a('getInfo',5);
我宁愿做这样的事情,也不愿在这里传递字符串(可能会改变):
Instead of passing a string here (which might change), I would prefer to do something like this:
$a(MyClass::class::getInfo,5);
我声明"在IDE中单击,我可以直接转到 getInfo
,此外,如果方法不再存在,我会看到错误.有什么方法可以实现我在这里要做的事情?
With I "go to declaration" click in the IDE I could go directly to getInfo
plus I see errors in case with method does not exist anymore. Is there a way to achieve what I want to do here?
推荐答案
实际上,您使用可调用类型.PHP只能将方法/函数名称设置为字符串.但是,如果您使用类和对象,则将有另一种设置回调的方法.例如:
In fact, you work with callable type. And PHP allows setting method/function name only as a string. But if you use classes and objects you will have a different way to set callback. For example:
$a = function($callback, $arg) {
return call_user_func($callback, $arg));
}
// call a static method of the class with
// using fullname space and method name as a string
$a('Name\Space\MyClass::getInfo',5);
// call a static method of the class
// with using ::class
$a([MyClass::class, 'getInfo'], 5);
// call a method of an object
$myObject = new MyClass();
$a([$myOject, 'getInfo'], 5);
这篇关于PHP回调:类的方法是否具有:: class的等效项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!