简体   繁体   English

如何将 PHP class 作为参数传递给构建器 function?

[英]How to pass PHP class as parameter to a builder function?

I implemented an object builder which takes a class name and tries to create a new instance object.我实现了一个 object 构建器,它采用 class 名称并尝试创建一个新实例 object。 The builder tries to inject services if any required.如果需要,构建器会尝试注入服务。 The class name is passed as a string in the current implementation. class 名称在当前实现中作为字符串传递。 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).但是,这与我的 IDE (eclipse) 不兼容,并且重构过程找不到 class 名称(字符串形式)。

Is there any way to get the class name like java does?有没有办法像 java 一样获得 class 名称?

Class classInstance = ServerClass.class;

In this case, the refactoring process finds the class reference and changes the class name.在这种情况下,重构过程会找到 class 引用并更改 class 名称。

Well, PHP7 class constant is supported on a class name.嗯,class 名称支持 PHP7 class 常量。 For example, the following code is correct in PHP 7.4:例如,以下代码在 PHP 7.4 中是正确的:

$service = CiContext::newInstance(\Example\Application\ServiceClass::class);

This will solve my problem and the IDE find the class usage.这将解决我的问题,并且 IDE 找到 class 用法。

On the other hand, the class literal is going to support for objects too.另一方面,class 文字也将支持对象。 For more information see class literal on object有关详细信息,请参阅object 上的 class 文字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM