我想问一下这是否可能:
我有一个带有私有构造函数的类,如果我试图从无效上下文(类外)实例化该类,它当然会抛出致命错误,我能抓住这个致命错误和类名,然后抛出一个异常吗
// 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:自定义错误处理程序-处理解析&致命错误
如果不可能,我应该公开构造函数,然后像这样在其中抛出和异常吗?:
public function __construct() {
throw new UninstantiableClassException("The class " . get_class($this) . " cannot be instantiated");
}
使用私有构造函数调用类将导致致命错误,因为构造函数总是被调用的。PHP没有捕获致命错误的内置函数,但您可以看看这里,看看如何捕获致命错误。
如何捕获PHP致命错误
这个例子应该给你一个如何使用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