php - 如何让 set_error_handler() 调用对象上的方法?

标签 php

我考虑使用 PHP 中的 set_error_handler() 功能在一个地方处理大部分 PHP 错误(将它们记录到文件中)。从文档看来,如果我可以将函数名称传递给 set_error_handler()。好的!但是我有一个 ErrorManager 对象,它有一个很好的日志记录方法。我想使用那个 ErrorManager 对象并为其编写一个特殊的错误处理程序方法,并让 set_error_handler 调用该 ErrorManager

我可以这样做吗?:

set_error_handler($this->customErrorHandler);

否则会无效吗?

最佳答案

传入一个对象数组和要调用的方法名:

set_error_handler(array($this, 'customErrorHandler'));

set_error_handler()需要 callback :

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.

(强调)

关于php - 如何让 set_error_handler() 调用对象上的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966817/

相关文章:

php - 这是否可以在没有互联网连接的情况下使用 recaptcha

php - 如何使用 PHP 获取 MySQL 的 'ft_min_word_len' 配置变量的值?

php - 我们什么时候应该在 PHP 中使用流包装器和套接字?

php - 如何保护流媒体视频不被下载

php - Paypal 错误 很抱歉,目前似乎无法正常工作

php - 如何使用php访问浏览器上可见的s3私有(private)图像

php - 如何确保SQL查询中的字段是唯一的?

php - 让 Doctrine 使用 MySQL "FORCE INDEX"

php - Guzzle 错误计数() : Parameter must be an array or an object that implements Countable in

php - 关联数组到 JSON