1. 程式人生 > >PHP名稱空間中使用全域性核心類報錯not found

PHP名稱空間中使用全域性核心類報錯not found

本博主轉載前必先親自考證,深惡痛絕百度CP之流,有問題請與我聯絡。

當一個php檔案聲明瞭名稱空間,則此檔案中使用類時,必須指定是在哪個名稱空間中,否則就會報錯,原因是在當前空間中找不到這個類,PHP核心類也會有這個問題,示例:

namespace TestExc;

try {
    throw new Exception('throw exception');
} catch(Exception $ex) {
    echo $ex->getMessage();
}

執行以上程式碼,報錯:

PHP Fatal error:  Class 'TestExc\Exception' not found inXXXX

從報錯中也可以看到,雖然Exception是PHP核心類,但程式只會在當前空間中尋找Exception類,有兩種解決方法

1. 宣告使用全域性空間的Exception

use \Exception;

2. 使用Exception時宣告為使用全域性空間的

namespace TestExc;
try {
    throw new \Exception('throw exception');
} catch(\Exception $ex) {
    echo $ex->getMessage();
}

相關知識:

如果沒有定義任何名稱空間,所有的類與函式的定義都是在全域性空間,與 PHP引入名稱空間概念前一樣。在名稱前加上字首 \ 表示該名稱是全域性空間中的名稱,即使該名稱位於其它的名稱空間中時也是如此。
對於函式和常量來說,如果當前名稱空間中不存在該函式或常量,PHP 會退而使用全域性空間中的函式或常量。
--------------------- 

原文:https://blog.csdn.net/lipengfeihb/article/details/54415237