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

前端 未结 3 460
你的背包
你的背包 2020-12-14 14:37

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

相关标签:
3条回答
  • 2020-12-14 15:08

    set_error_handler accepts a callback as parameter.

    Quoting that page :

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


    In your case, you want a callback that corresponds to a method (Called 'customErrorHandler') of an object (here, $this) ; the callback would then be :

    array($this, 'customErrorHandler')
    

    So, you'd use this portion of code :

    set_error_handler(array($this, 'customErrorHandler'));
    
    0 讨论(0)
  • 2020-12-14 15:19

    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)

    0 讨论(0)
  • 2020-12-14 15:22

    In PHP 5.3 you could do it in a closure:

    $that = $this;
    set_error_handler( function() use ($that) { $that->customErrorHandler(); } );
    
    0 讨论(0)
提交回复
热议问题