Alex
Alex

Reputation: 44305

Make undefined variable an error in php

I have the following code snippet:

<?php
ini_set('display_errors', '1');
error_reporting(E_ALL | E_NOTICE);
print $bla;
print 7;
?>

which prints out a warning that bla is undefined, but continues afterwards. I want php to throw an error and stop code execution when an undefined variable is encountered. How to do that?

The above is just an example. I want to handle EACH undefined variable within a multi thousand block clode piece.

Upvotes: 2

Views: 431

Answers (3)

tlenss
tlenss

Reputation: 2609

You could write your own error handler. And make it halt execution when you encounter this type of notice. Take a look at

http://php.net/manual/en/function.set-error-handler.php

A small and simple example:

function new_error_handler($errno, $errstr, $errfile, $errline) {
    switch ($errno) {
      case E_NOTICE:
        if (strstr($errstr, 'Undefined variable')) {
          die('Undefined variable found');
        }
      break;
    }
}

set_error_handler('new_error_handler');

echo $foo;

Upvotes: 5

Agrest
Agrest

Reputation: 234

if(!isset($bla)){
   throw new Exception('bla variable is not defined');
}

Upvotes: -1

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

Implement an error handler with set_error_handler and put a die inside.

Upvotes: 2

Related Questions