【问题标题】:Catch the PHP private __constructor fatal error and throw an exception PHP? [duplicate]捕获 PHP 私有 __constructor 致命错误并抛出异常 PHP? [复制]
【发布时间】:2014-12-26 02:25:47
【问题描述】:

我想问这是否可能:

我有一个带有私有构造函数的类,如果我尝试从无效上下文(类外部)实例化该类,它当然会引发致命错误,我可以捕获这个致命错误和类的名称然后抛出像这样的例外:

// 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 function __construct() {
   throw new UninstantiableClassException("The class " . get_class($this) . " cannot be instantiated");
}

【问题讨论】:

  • 其实我不认为这是一个重复的问题,我已经阅读了@user259973 对该帖子的回答。在他的回答中,他说应该使用 register_shutdown_function,但是即使调用register_shutdown_function(),在调用 register_shutdown_function() 之前,致命错误仍然会出现在屏幕上,所以我的问题是是否有一种方法可以使该致命错误不会在出现问题时出现在屏幕上,而是制作一个自定义的致命错误处理程序......希望你能理解。

标签: php exception private fatal-error


【解决方案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

【讨论】:

  • 谢谢你的帖子,所以如果我实现一个 register_shutdown_function() 这样你喜欢我的帖子的人,我用 error_get_last() 我可以捕捉到每个错误吗?然后我应该查看错误是否属于 1 类(E_ERROR,因此是致命错误)并在 ['message'] 字段中搜索模式,例如~^Call\sto\sprivate*?::__construct()\sfrom invalid\scontext$~,对吗?无论如何,还有一种方法可以使原始的 E_ERROR 致命错误不出现,而是只显示一条自定义消息(我的意思是不更改 conf php.ini 文件)?
猜你喜欢
  • 1970-01-01
  • 2012-10-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多