Instantiating class by string in current namespace

前端 未结 1 806
南方客
南方客 2021-02-09 00:34

I\'m trying to instantiate an object of a dynamically created classname. I\'m using namespaces and the class I want to instantiate is in the same namespace.

To examplify

1条回答
  •  鱼传尺愫
    2021-02-09 01:08

    When you use a string with new you need to provide a fully qualified class name.

    You can do this with __NAMESPACE__:

    $fullclass = __NAMESPACE__ . '\\' . $class;
    new $fullclass;
    

    See the documentation for the new operator and the __NAMESPACE__ magic constant.

    0 讨论(0)
提交回复
热议问题