Search code examples
javaphpdynamicbuilder

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. 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.


Solution

  • 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