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?
Kind of. You can activate the
E_NOTICElevel in your error reporting. (List of constants here.)Every instance of usage of an undeclared variable will throw an
E_NOTICE.The
E_STRICTerror level will also throw those notices, as well as other hints on how to optimize your code.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: