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?
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.
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.
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”.
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.
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_NOTICE
s 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 ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With