views:

872

answers:

2

Hello, I am trying to implement Type Hinting of PHP5 on one of my class,

class ClassA {
    public function method_a (ClassB $b)
    {}
}

class ClassB {}
class ClassWrong{}

Correct usage:

$a = new ClassA;
$a->method_a(new ClassB);

producing error:

$a = new ClassA;
$a->method_a(new ClassWrong);

Catchable fatal error: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassWrong given...

May I know if it is possible to catch that error(since it says "catchable")? and if yes, how?

Thank you.

+8  A: 

http://docs.php.net/errorfunc.constants says:

E_RECOVERABLE_ERROR ( integer )
Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.

see also: http://derickrethans.nl/erecoverableerror.html

e.g.

function myErrorHandler($errno, $errstr, $errfile, $errline) {
  if ( E_RECOVERABLE_ERROR===$errno ) {
    echo "'catched' catchable fatal error\n";
    return true;
  }
  return false;
}
set_error_handler('myErrorHandler');

class ClassA {
  public function method_a (ClassB $b) {}
}

class ClassWrong{}

$a = new ClassA;
$a->method_a(new ClassWrong);
echo 'done.';

prints

'catched' catchable fatal error
done.

edit: But you can "make" it an exception you can handle with a try-catch block

function myErrorHandler($errno, $errstr, $errfile, $errline) {
  if ( E_RECOVERABLE_ERROR===$errno ) {
    echo "'catched' catchable fatal error\n";
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    // return true;
  }
  return false;
}
set_error_handler('myErrorHandler');

class ClassA {
  public function method_a (ClassB $b) {}
}

class ClassWrong{}

try{
  $a = new ClassA;
  $a->method_a(new ClassWrong);
}
catch(Exception $ex) {
  echo "catched\n";
}
echo 'done.';

see: http://docs.php.net/ErrorException

VolkerK
Thanks! I learn a new thing!
hoball
A: 

this is really very nice

aamir