一個關於PHP命名空間的疑惑

來源:互聯網
上載者:User
在編程的時候遇到這樣一個關於命名空間的問題,先上代碼:

namespace Test {    class Test {}}namespace Chou {    use Test\Test;    class Mee {        public $class = 'Test';        public function getClass()        {            return new $this->class();        }    }    $tmp = new Mee();    $tmp->getClass();}

我試圖在getClass方法中通過變數動態執行個體化另一個命名空間的類,但是觸發了“Class not found”錯誤。我覺得時$class變數的問題,所以又把測試代碼簡化了一下:

namespace Chou {    use Test\Test;    $test = 'Test';    $tmp = new $test();}

果然出現了和預期一樣的錯誤。我知道可以通過完整方式來解決,但是我仍然想明白這是什麼原理,還望高手解惑。

是我自己疏忽了,在手冊中找了命名空間和動態語言特徵

回複內容:

在編程的時候遇到這樣一個關於命名空間的問題,先上代碼:

namespace Test {    class Test {}}namespace Chou {    use Test\Test;    class Mee {        public $class = 'Test';        public function getClass()        {            return new $this->class();        }    }    $tmp = new Mee();    $tmp->getClass();}

我試圖在getClass方法中通過變數動態執行個體化另一個命名空間的類,但是觸發了“Class not found”錯誤。我覺得時$class變數的問題,所以又把測試代碼簡化了一下:

namespace Chou {    use Test\Test;    $test = 'Test';    $tmp = new $test();}

果然出現了和預期一樣的錯誤。我知道可以通過完整方式來解決,但是我仍然想明白這是什麼原理,還望高手解惑。

是我自己疏忽了,在手冊中找了命名空間和動態語言特徵

手冊裡有寫,在變數中使用命名空間必須使用完全限定名稱,規定如此。

http://php.net/manual/zh/language.nam...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.