• Date: August 9, 2011
  • Author: Slawek Lukasiewicz
  • Comments: 4 Comments
  • Category: PHP

One of the most annoying behavior of PHP type hinting feature is triggering error instead of throwing exception when instance type is invalid.

class Test
{
 
	public function doSomething(A $a) { #code}
}
 
class B {}
 
$testInstance = new Test();
$bInstance = new B();
$testInstance->doSomething($bInstance);

Above code will interrupt script with catchable fatal error.

Catchable fatal error: Argument 1 passed to Test::doSomething() must be an instance of A, instance of B given…[etc]

Luckily, there is solution to bypassing this behavior. We can use custom error handler and throw exception alone. Custom error handler gives us possibility to handle errors.

Catchable fatal error is an error represented by E_RECOVERABLE_ERROR constant, and described by manual as:

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.

This means, that it will not interrupt our script, when we handle it.

Using error handler is quite easy. We have to define function and register it using set_error_handler.

function errorHandler($errno, $errstr, $errfile, $errline) {
 
	if ( $errno === E_RECOVERABLE_ERROR ) { 
		throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
	}
 
	return false;
}
 
set_error_handler('errorHandler');

After registration we can use try .. catch block to deal with type hinting exceptions.

$testInstance = new Test();
$bInstance = new B();
try {
 $testInstance->doSomething($bInstance);
} catch(ErrorException $e) {}

ErrorException

As you can see above, I used ErrorException class as exception. This is very neat class! In standard case, Exception class will return line and file name connected with place, where exception was thrown. In our example – line and filename are connected with errorHandler function.

On the other hand, ErrorException uses line and file name passed as constructor arguments, so in our example they are connected with doSomething method in Test class. It is much better for debugging process.

Custom Exception class

Of course we can use custom class for incorrect type exception. It can be done by extracting information from error message. Type hinting custom exception can extend some of SPL exceptions.

4 Responses to “Throwing exception when type hinting failed”

  1. ichr says:

    good article.

    anyway, the menu item ‘HOME’ at the top wants to redirect me to ‘http:///#’

  2. Slawek Lukasiewicz says:

    Franky speaking I am not sure if I want to give possibility to suppress such situations ;) But thanks for your comment!

  3. you are lucky if you don’t need high quality software ร  la ZendFramework ;)

Leave a Reply →