Pavel S.
Pavel S.

Reputation: 12332

PHP - pass an extra parameter (variable) to set_exception_handler

Is there any way to pass variable to the set_exception_handler() method in PHP? I need something like this:

class Clazz {

    public /* static */ function foo() {
        set_exception_handler(array('Clazz', 'callback'), $var); // I need to pass $var

         // or this in non-static context
         $that = $this;
         set_exception_handler(array($that, 'callback'), $var); // I need to pass $var
    }

    public static function callback($exception, $var) {
        // process $exception using $var
    }
}

Upvotes: 4

Views: 4771

Answers (3)

fredtma
fredtma

Reputation: 1053

Use a callback

set_exception_handler(function($exception) use($var){
    $that->callback($exception, $var);
});

Upvotes: 2

Martin Dimitrov
Martin Dimitrov

Reputation: 4956

One possibility is to catch the exception and re-throw a derived one which has this custom property.

class MyLibraryException extends LibraryException {
    function __construct(LibraryException $e, $custom_field){
         $this->custom_field = $custom_field;
         ...
    }
}

try {
    ...
} catch(LibraryException $e) {
    new MyLibraryException($e, $cusotm_field);
}

Upvotes: 1

androidavid
androidavid

Reputation: 1259

As i already indicated in the comment you have to use lambda-functions anyway:

 $lambda = function($exception) use ($var) {
    Clazz::callback($exception,$var);
 }

 set_exception_handler($lambda);

Upvotes: 9

Related Questions