Php 尝试在类';中引发新异常时出错;建造师
我有这门课Php 尝试在类';中引发新异常时出错;建造师,php,class,exception,constructor,exception-handling,Php,Class,Exception,Constructor,Exception Handling,我有这门课 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
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');
我希望它能显示出,“noteathing”不是一种有效的实体类型,而是
致命错误:在{line}行的{root/to/my/file}中找不到类“core\Exception”
我遗漏了什么吗?您正在使用名称空间核心
因此,使用抛出新异常
意味着在当前命名空间
下使用抛出新异常
类,而不是使用抛出新异常
将此更改为:
throw new Exception("'".$type."' is not a valid type of entity.");
throw new \Exception("'".$type."' is not a valid type of entity.");
这个:
throw new Exception("'".$type."' is not a valid type of entity.");
throw new \Exception("'".$type."' is not a valid type of entity.");