Skip to content

Latest commit

 

History

History
159 lines (119 loc) · 7.26 KB

09-02-01-Errors.md

File metadata and controls

159 lines (119 loc) · 7.26 KB
isChild anchor
true
errors

Errors {#errors_title}

In many "exception-heavy" programming languages, whenever anything goes wrong an exception will be thrown. This is certainly a viable way to do things, but PHP is an "exception-light" programming language. While it does have exceptions and more of the core is starting to use them when working with objects, most of PHP itself will try to keep processing regardless of what happens, unless a fatal error occurs.

For example:

{% highlight console %} $ php -a php > echo $foo; Notice: Undefined variable: foo in php shell code on line 1 {% endhighlight %}

This is only a notice error, and PHP will happily carry on. This can be confusing for those coming from "exception-heavy" languages, because referencing a missing variable in Python for example will throw an exception:

{% highlight console %} $ python

print foo Traceback (most recent call last): File "", line 1, in NameError: name 'foo' is not defined {% endhighlight %}

The only real difference is that Python will freak out over any small thing, so that developers can be super sure any potential issue or edge-case is caught, whereas PHP will keep on processing unless something extreme happens, at which point it will throw an error and report it.

Error Severity

PHP has several levels of error severity. The three most common types of messages are errors, notices and warnings. These have different levels of severity; E_ERROR, E_NOTICE, and E_WARNING. Errors are fatal run-time errors and are usually caused by faults in your code and need to be fixed as they'll cause PHP to stop executing. Notices are advisory messages caused by code that may or may not cause problems during the execution of the script, execution is not halted. Warnings are non-fatal errors, execution of the script will not be halted.

Another type of error message reported at compile time are E_STRICT messages. These messages are used to suggest changes to your code to help ensure best interoperability and forward compatibility with upcoming versions of PHP.

Changing PHP's Error Reporting Behaviour

Error Reporting can be changed by using PHP settings and/or PHP function calls. Using the built in PHP function error_reporting() you can set the level of errors for the duration of the script execution by passing one of the predefined error level constants, meaning if you only want to see Warnings and Errors - but not Notices - then you can configure that:

{% highlight php %}