PHP’s error handling mechanism
PHP’s error handling is relatively complicated. This article explains all the important knowledge points related to errors in PHP to make it easier to understand PHP’s error mechanism.
Basic knowledge
Before this, familiarize yourself with the basic knowledge of php error
Predefined constants
Runtime Configuration
Exception
Error handling function
Predefined constants
Defines all PHP error type constants. Each constant is an integer value. Its function is that the value (numeric value or symbol) above
is used to create a binary bit mask to Specify the error message to be reported. You can use bitwise operators to combine these values or to mask certain types of errors. Please note that in php.ini, only '|', '~', '!', '^' and '&' will be parsed correctly.
From the perspective of usage, it can be divided into three categories:
thrown manually by the user
E_USER_NOTICE
,E_USER_WARNING
,E_USER_ERROR
,E_USER_DEPRECATED
User-caused
E_NOTICE
,E_PARSE
,E_WARNING
,E_ERROR
,E_COMPILE_ERROR
,E_COMPILE_WARNING
,E_STRICT
,E_RECOVERABLE_ERROR
E_CORE_ERROR
,E_CORE_WARNING
caused by the php kernel From the perspective of whether to terminate program execution, it can be divided into two categories
Termination of program execution
The program terminates and enters the error handling processDoes not terminate program execution
An error occurs, but the program can still continue to execute and also enter the error handling process
For error types in PHP, you can refer to this more detailed article- -Summary of PHP's error mechanism
Runtime configuration
Manual--The runtime configuration is explained in detail, but there are several configurations that still require special attention
-
error_reporting
Reporting error type, it is recommended to configureE_ALL
in the development/testing environment. After solving all types of errors, configureE_ALL in the production environment & E_DEPRECATED
, indicates: report all errors except discarded errors ##display_errors
Whether to display errors, configure it to false in the production environment , combined with the settings of
error_reportingabove, it means: report all errors except discarded errors, but do not display error messages.
- ##log_errors
Whether error logging is turned on,
The production environment needs to be turned on
. With the above two configurations, it means: report all errors except discarded errors, do not display error messages, but record (only PHP itself can Operation error information) to the log. - error_log
Specify the error file
(syslog is a special value)
. The default is not Settings, in the manual:
If this configuration is not set, error messages will be sent to the SAPI error loggerReport all errors except discard errors, do not display error information, but record it to theGenerally, if not set, it will be recorded in the apache/nginx error log. With the above three configurations, it means: report all errors except obsolete errors, do not display error information, but record it in the apache/nginx log Medium. If the file path is configured, it means:
file_dirlog.
The above configurations affect the most basic performance of php errors. Of course, these configurations can be changed in the code through
or php-fpm configuration changesError handling function
There are not many error functions. The ones you should pay most attention to are
set_error_handler and set_exception_handler
, because they can intervene in the error/exception processing process.
Let’s first look at the explanation in the PHP manual: Errors
In simple terms That is,
The default processing flow is completed through configuration, but we can set a custom error handling flowHow to handle errors that terminate script execution
As mentioned in the article, there are two kinds of errors. So how to deal with this kind of error that will terminate the execution of the script?
set_error_handler
cannot handle this kind of error, which is easy to be ignored. So we need to find another One method.This problem is basically solved like this (have not seen other solutions yet):
// 终止脚本的错误会终止脚本执行 // 即会调用已通过register_shutdown_function注册的处理函数 // 由此可注册我们的错误处理流程, 这样就进入了自定义错误流程 register_shutdown_function('FatalErrorHandle'); ... FatalErrorHandle(array $error = null) { ... if (null === $error) { // 通过这种方式可以获取最后一条错误 $error = error_get_last(); } ... // log or other logic }
Exception
According to the explanation in w3cPHP exception handling:
Exception handling is used to change the normal flow of the script when a specified error (exception) situation occurs. This situation is called an exception.When an exception is triggered, what usually happens is:
The current code state is saved
- Code execution is switched to the predefined Exception handler function
Depending on the situation, the processor may restart code execution from a saved code state, terminate script execution, or continue script execution from a location outside the code
Uncaught exceptions will terminate script execution and generate an E-ERROR error. The defined exception handling will be performed. If not, the default error handling process of PHP will be performed, which is recorded in the log. However, in terms of programming concepts, it should be Separate exceptions from errors. Exceptions are predictable to users, do not meet expectations, and are controllable structures.
set_exception_handler
mentioned above is used to handle exceptions. Usage Consistent with set_error_handler
. The exception handling in each framework is very mature. Generally speaking, set_exception_handler
will transfer Exception
to the framework handleable level, and the framework will also Open good interfaces for users to use, so as to achieve the purpose of user control of exception handling and realize customization and expansion.
Summary
php's error handling mechanism is always ignored, but it is useful for debugging. Monitoring errors plays a great role. This article mainly introduces the main knowledge points and makes a summary. I hope it will be useful to everyone. For more details, please check the manual.
Learning Materials
Predefined constants
Runtime configuration
Error handling function
Summary of PHP's error mechanism
Exceptions
Errors
PHP exception handling
Symfony Debug: is a complete application , it can be said to be a comprehensive tutorial, covering all error-related knowledge points. It is recommended to read the source code.
The above is the detailed content of PHP error handling issues. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools