Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict mode in PHP

Other languages with automatic variable declaration - like Perl - have a strict mode.

By activating this strict mode, variable declaration is required, and Perl throws an error as soon as you try to use an undeclared variable.

Does PHP offer a similar feature?

like image 877
jantimon Avatar asked Jul 07 '10 08:07

jantimon


People also ask

What is strict type checking?

Strict type checking means the function prototype(function signature) must be known for each function that is called and the called function must match the function prototype. It is done at compile time.

What is the purpose declare Strict_types 1 function in PHP?

When passing an unexpected type to a function, PHP will attempt to automatically cast the value to the expected type. If strict_types has been declared then PHP will throw an exception instead. Using declare(strict_types=1) will tell PHP to throw type errors when you try to (accidentally) cast primitive values.

What is weak type in PHP?

For instance, a function that is given a float for a parameter that expects an integer will get a variable of type integer . In other words, PHP will try to “fallback” to the target type from the given type whenever it can. This is called “weak typing”.

What is strict and Nonstrict mode in JavaScript?

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.


1 Answers

Kind of. You can activate the E_NOTICE level in your error reporting. (List of constants here.)

Every instance of usage of an undeclared variable will throw an E_NOTICE.

The E_STRICT error level will also throw those notices, as well as other hints on how to optimize your code.

error_reporting(E_STRICT); 

Terminating the script

If you are really serious, and want your script to terminate instead of just outputting a notice when encountering an undeclared variable, you could build a custom error handler.

A working example that handles only E_NOTICEs with "Undefined variable" in them and passes everything else on to the default PHP error handler:

<?php  error_reporting(E_STRICT);  function terminate_missing_variables($errno, $errstr, $errfile, $errline) {                                  if (($errno == E_NOTICE) and (strstr($errstr, "Undefined variable")))    die ("$errstr in $errfile line $errline");    return false; // Let the PHP error handler handle all the rest   }  $old_error_handler = set_error_handler("terminate_missing_variables");   echo $test; // Will throw custom error  xxxx();  // Will throw standard PHP error   ?> 
like image 142
Pekka Avatar answered Sep 19 '22 14:09

Pekka