2017-04-03 49 views
1

我有這個類錯誤,而試圖在課堂上拋出新的異常的構造函數

namespace core; 

class Entity { 

    private $type; 

    public function __construct($type, $source=null){ 
     if($this::isValidType($type)){ 
      $this->type = $type; 
     }else{ 
      throw new Exception("'".$type."' is not a valid type of entity."); 
     } 
    } 


    private static function isValidType($type){ 
     return in_array($type, array(
      'Thing', 
     )); 
    } 
} 

然後我用這個代碼:

$thing = new core\Entity('Not a Thing'); 

而且我希望它顯示"Not a Thing" is not a valid Type of entity而是我得到

Fatal Error: Class 'core\Exception' not found in {root/to/my/file} on line {line}`.

我錯過了什麼嗎?

回答

2

您使用namespace core;所以使用throw new Exception指根據當前namespaceException類,而是使用throw new \Exception

更改爲:

throw new Exception("'".$type."' is not a valid type of entity."); 

此:

throw new \Exception("'".$type."' is not a valid type of entity."); 
+0

哦!嗯你是對的!謝謝。 – thingNumber2

+0

@ thingNumber2歡迎... :) –

相關問題