我想问一下这是否可行:
我有一个带有私有构造函数的类,如果我尝试从无效的上下文(类外)实例化该类,当然会抛出一个致命的错误,我可以捕获这个致命的错误和类的名称然后抛出一个例外:
// catch the private constructor from invalid context fatal error
// and store somehow the name of the class inside $class
// and then:
throw new UninstantiableClassException("The class " . $class . " cannot be instantiated");
这可能,或者基于这篇文章,我刚发现它不是吗? - > PHP : Custom error handler - handling parse & fatal errors
如果不可能,我应该将构造函数设为public,然后像这样抛出异常吗?:
public function __construct() {
throw new UninstantiableClassException("The class " . get_class($this) . " cannot be instantiated");
}
答案 0 :(得分:1)
使用私有构造函数调用类将导致致命错误,因为始终会调用构造函数。 PHP没有内置函数来捕获致命错误,但你可以看一看如何捕获致命错误。
How do I catch a PHP Fatal Error
这个例子可以让你对如何使用register_shutdown_function
有一个很好的印象class Test
{
private function __construct()
{
throw new UninstantiableClassException("The class " . get_class($this) . " cannot be instantiated");
}
}
register_shutdown_function('shutdownFunction');
function shutDownFunction() {
$error = error_get_last();
if ($error['type'] == 1) {
$error['message'] = 'Your message here';
var_dump($error);
}
}
$foo = new Test();
var_dump($error)
的输出将为:
array (size=4)
'type' => int 1
'message' => string 'Your message here' (length=17)
'file' => string '/var/www/test.php' (length=21)
'line' => int 21