【问题标题】:Error while trying to throw new Exception in class' constructor尝试在类的构造函数中抛出新异常时出错
【发布时间】:2017-08-28 14:55:07
【问题描述】:

我有这门课

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 但我却得到了

致命错误:在第 {line} 行的 {root/to/my/file} 中找不到类“core\Exception”。

我错过了什么吗?

【问题讨论】:

    标签: php class exception constructor exception-handling


    【解决方案1】:

    您正在使用namespace core;,因此使用throw new Exception 表示当前Exception 下的Exception 类,而不是使用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.");
    

    【讨论】:

      猜你喜欢
      • 2014-11-03
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      相关资源
      最近更新 更多