Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

php - How can I make set_error_handler() call a method on an object?

I think about using the set_error_handler() functionality in PHP to handle most of the PHP errors in one place (logging them to a file). From the documentation it looks like if I can pass a function name to set_error_handler(). Nice! But I have an ErrorManager object which has a nice logging method. I want to use that ErrorManager object and write an special error handler method for it, and have set_error_handler call that ErrorManager.

Could I just do something like?:

set_error_handler($this->customErrorHandler);

Or would that be invalid?

question from:https://stackoverflow.com/questions/1966817/how-can-i-make-set-error-handler-call-a-method-on-an-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Pass in an array of the object and the method name to be called:

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

set_error_handler() takes a 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.

(emphasis added)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...