动态创建新类的正确方法是什么


What is right way to create new class dynamically?

我有下一个目录树:

运输
--Transport.php
--Curl.php

SDK.php

SDK.php是名称空间MySDK和类SDK,在该类中我有方法:

protected function _getTransport()
{
    if (!($this->_transport instanceof Transport'Transport)) {
        $className = 'Transport''' . ucfirst($this->getOption('transport'));
        $this->_transport = new $className();
    }
    return $this->_transport;
}

但我收到错误消息:致命错误:在/path/to/repo/lib/SDK.php中找不到类"Transport''Coll"当我把$this->_transport = new $className();改为$this->_transport = new Transport'Curl();时,我会很好地得到Transport'Curl的实例。

请帮帮我,我哪里搞错了?

您应该以'或前缀名称空间开始,就像具有动态类名的PHP名称空间一样

$className = '''Transport''' . ucfirst($this->getOption('transport'));