英文:
How to pass PHP class as parameter to a builder function?
问题
我实现了一个对象构建器,它接受一个类名并尝试创建一个新的实例对象。构建器会在必要时注入所需的服务。在当前的实现中,类名以字符串形式传递。以下是一个示例:
$className = '\Example\Application\ServiceClass';
$service = CiContext::newInstance($className);
然而,这与我的 IDE(eclipse)不兼容,重构过程无法找到字符串形式中的类名。
是否有办法像 Java 一样获取类名?
Class classInstance = ServerClass.class;
在这种情况下,重构过程会找到类引用并更改类名。
英文:
I implemented an object builder which takes a class name and tries to create a new instance object. The builder tries to inject services if any required. The class name is passed as a string in the current implementation. Here is an example
$className = '\Example\Application\ServiceClass';
$service = CiContext::newInstance($className);
However, this is not compatible with my IDE (eclipse) and the refactoring process does not find the class name (in the string form).
Is there any way to get the class name like java does?
Class classInstance = ServerClass.class;
In this case, the refactoring process finds the class reference and changes the class name.
答案1
得分: 0
好的,以下是翻译好的内容:
PHP7支持在类名上使用类常量。例如,以下代码在PHP 7.4中是正确的:
$service = CiContext::newInstance(\Example\Application\ServiceClass::class);
这将解决我的问题,并且IDE能够找到类的用法。
另一方面,类字面量也将支持对象。更多信息请参见对象上的类字面量。
英文:
Well, PHP7 class constant is supported on a class name. For example, the following code is correct in PHP 7.4:
$service = CiContext::newInstance(\Example\Application\ServiceClass::class);
This will solve my problem and the IDE find the class usage.
On the other hand, the class literal is going to support for objects too. For more information see class literal on object
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论