PHP E_NOTICE
Notices are non-fetal errors in the code that often does not prevent execution. From a developers point of view, they are sometimes intentional.
By. Jacob
Edited: 2020-09-24 08:45
E_NOTICE messages are not serious and can often be ignored, but it is generally considered a good practice to fix them anyway. Typically notice messages will be triggered because of minor mistakes in the code, such as using a variable before declaring it, which is often not an error; still, PHP will notify you about it depending on the error reporting level.
To only show E_NOTICE errors, you may use the error_reporting function:
error_reporting(E_NOTICE);
You would typically want to display more than just notices while coding. It is recommended to show all errors E_ALL on your development environment, and then fix everything so your code can run without producing errors.
error_reporting(E_ALL);
Custom error messages
E_NOTICE also has the corresponding user-generated E_USER_NOTICE, we should use that when triggering custom notices. But, it is usually better to throw an exception, since those can be handled by users of our code with try and catch blocks.
trigger_error("You should normally call method x before calling method y", E_USER_NOTICE);
Triggering a notice message is probably suitable if a user needs to call certain parts of your code before calling the next; you can perform a conditional check to see if the code was called properly, and then trigger a notice message if not. There might still be valid reasons why a user is calling your code in an unintended manner, so a notice message is suitable in this case; but again, throwing an exception is more concise.
Causes
An E_NOTICE error is commonly triggered by using a variable before declaring it; this will trigger a message like the below:
Notice: Undefined variable: test in /var/www/testing.php on line 14
This tells us that the variable $test was used before being declared, and that the error was triggered on line 14 in the testing.php file — this information should be enough for us to open the file in our editor and fix the error. To fix the error, we would probably need to declare the variable before using it, which can be done like this:
$test = '';
Tell us what you think: