


Do you know how to customize error handling functions and error masking in PHP?
In the previous article, I brought you "Take you to understand the error types and error levels of PHP", which introduced the error types and error levels in PHP in detail. In this article we Let’s take a look at how to customize error handling and how to block errors in PHP. I hope it will be helpful to everyone!
In our daily development, it is inevitable to encounter errors. Sometimes we can specify a function as an error handling function. There is a custom error in PHP processing function.
<strong><span style="font-size: 20px;">set_error_handler() </span></strong>
##Function custom error handling function
set_error_handler(自定义函数名 [, int $error_types = E_ALL | E_STRICT ])The syntax format of this custom function name is as follows:
error_handler(int 错误的级别 , string 错误的信息 [, string 发生错误的文件名 [, int 发生错误的行号 ]])If there is an error handler defined before, the returned program name is the program name of the modified program; if it is a built-in error handler, the returned result is NULL. If an invalid callback function is specified, NULL will also be returned.
<?php function error_handler($errno, $errstr, $errfile, $errline ) { echo "error number:".$errno."<br/>"; echo "error msg:".$errstr."<br/>"; echo "error file:".$errfile."<br/>"; echo "error line:".$errline."<br/>"; die('something error'); } set_error_handler("error_handler"); strpos(); ?>Output results :
<?php function error_handler($errno, $errstr, $errfile, $errline ) { echo "error number:".$errno."<br/>"; echo "error msg:".$errstr."<br/>"; echo "error file:".$errfile."<br/>"; echo "error line:".$errline."<br/>"; die('something error'); } set_error_handler("error_handler"); /* 触发异常 */ try { $a = 5/0;//程序会自动捕捉这个异常,并且由自定义函数来处理 echo $a; } catch(Exception $e) { echo $e->getMessage(); } ?>Output result:
##Error maskingIn the PHP development process, we can not only handle errors by customizing the error handling function through set_error_handler(), but we can also mask errors. In some cases, error masking is also essential. Next, I will list some methods for error shielding.
-
In PHP, if the error control operator @ is placed in front of an expression, any errors that may exist in the expression will be blocked.@<span style="font-size: 16px;"><strong></strong></span>##---Error control operator
Regarding the use of @, we need to note that the @ operator will only take effect when placed in front of an expression. For example, the @ operator can be used in front of variables, functions, constants, etc. , must not be placed before the definition of a function or class, nor can it be placed in front of a conditional structure statement.
<?php $link = @mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db") or die('数据库连接失败!'); ?>
Output result:
In the above example, it can be seen that @ Error control operator, which can mask expressions before expressions.
- Use
error_reporting() Function to shield errors
##PHP There are many error levels in PHP. You can use the error_reporting() function to set what kind of errors PHP will report. The syntax format of the function is as follows:
error_reporting(设置错误级别)
Regarding the error levels, please learn about them in the previous article "
<?php error_reporting(0); $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db") or die('数据库连接失败!'); ?>
##Mask errors through the
- parameter
-
php.iniThis method is the most thorough method. The first two methods only work on a single line or a single file, but masking errors through the display_errors parameter works on all PHP files. Let’s take a look at what to do. Do it. First we need to open the
configuration file, then find display_errors, set its value to Off to turn off all PHP error reports.
(In the previous article "How to upload files in PHP? You will understand after reading it!" introduced the relevant knowledge on how to remove php and ini configuration files)
Examples are as follows:
This way you can block errors.
If you are interested, you can click on "PHP Video Tutorial" to learn more about PHP knowledge.
The above is the detailed content of Do you know how to customize error handling functions and error masking in PHP?. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)
