13

I RTM but I couldn't find any nice answer to this question, so here is it:

  • Can I call a static method as an error handler (for example: set_error_handler('error::function'))?
  • Is it recommended?

2 Answers 2

20

set_error_handler expects a value of the pseudo-type callback. And in the examples there you can see that there are two ways to specify a static method:

set_error_handler(array('Class', 'method'));

// since PHP 5.2.3
set_error_handler('Class::method');
5
  • What if a have an autoload function for classes and the class in class::method is not yet included? Does PHP autoload it?
    – Shoe
    Jan 23, 2011 at 11:42
  • @Charlie Pigarelli: I don’t know. Why don’t you try it?
    – Gumbo
    Jan 23, 2011 at 11:43
  • Note that using self::method doesn't work. The Class name must be specified.
    – payling
    Aug 16, 2011 at 19:18
  • 3
    If you are using PHP namespaces be sure to include the full namespace to your class. I.e. set_error_handler('MyNameSpaceRoot\MyNameSpacePath\MyErrorClass::myErrorHandlerMethod'); or in the other form: set_error_handler(array('MyNameSpaceRoot\MyNameSpacePath\MyErrorClass', 'myErrorHandlerMethod')); Oct 7, 2013 at 16:17
  • Note that if you are using a namespace, include it in the actual string; a "use" statement will have no effect. Aug 21, 2019 at 11:37
2

Yes; this syntax works:

set_error_handler('error::function');

As stated in the doc, you just have to pass a valid callback. http://php.net/manual/en/language.pseudo-types.php#language.types.callback(dead link)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.