2015-11-06 72 views
0

我有未來的目錄樹:動態創建新類的正確方法是什麼?

Transport
--Transport.php
--Curl.php

SDK.php

SDK.php是命名空間MySDK和類SDK,在I類有方法:

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

但我收到錯誤消息:致命錯誤:類' Transport \ Curl'找不到/path/to/repo/lib/SDK.php 而當我將$this->_transport = new $className();更改爲$this->_transport = new Transport\Curl();時,我將獲得Transport\Curl的實例。

請幫助我,我在哪裏犯錯?

+0

哪裏是你的類自動加載磁帶機? – Flosculus

+0

聽起來像名稱空間問題。你在使用作曲家和PSR-0或PSR-4嗎? – mblaettermann

回答

0

你應該用\或前綴命名空間開始按PHP namespace with Dynamic class name

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

正確。但是不清楚OP是否使用'\\ MySDK'\\ Transport \\'。 ucfirst($ this-> getOption('transport'));'或\'\\ Transport \\'。 ucfirst($ this-> getOption('transport'));' – mblaettermann

+0

什麼是更好的方法? – Dmitro

+0

當我寫了'__NAMESPACE__。 '\\運輸\\' 。 ucfirst($ this-> getOption('transport'))'它變成了工作。 – Dmitro

相關問題