How to catch an "undefined index" E_NOTICE error in simpleTest?

Viewed 24063

I would like to write a test using simpleTest that would fail if the method I'm testing results in a PHP E_NOTICE "undefined index : foo".

I tried expectError() and expectException() without success. The simpleTest webpage indicate that simpleTest isn't able to catch compile time PHP errors, but E_NOTICE seems to be a run time error.

Is there a way to catch such an error and makes my test fail if so ?

4 Answers

You'll never catch it within the try-catch block, luckily we have set_error_handler():

<?php
function my_handle(){}
set_error_handler("my_handle");
echo $foo["bar"];
?>

You can do anything you want inside my_handle() function, or just leave it empty to silence the notice, although, it's not recommended. A normal handler should be like this:

function myErrorHandler($errno, $errstr, $errfile, $errline)

Many solutions to handling at sign E_NOTICE errors ignore all E_NOTICE errors. To ignore just errors due to use of at signs, do this in your set_error_handler callback function:

if (error_reporting()==0 && $errno==E_NOTICE)
    return; // Ignore notices for at sign

An example of an important E_NOTICE that should not be ignored is this:

$a=$b;

because $b is undefined.

Related