我考虑使用 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/