


Exception handling mechanism of php5 and php7 (analysis of thinkphp5 exception handling)
This article mainly introduces the exception handling mechanism of php5 and php7 (analysis of thinkphp5 exception handling). I hope it will be helpful to friends in need!
1.php exceptions and errors
In other languages, exceptions and errors are different, but PHP will trigger an error when it encounters its own error. Instead of throwing an exception. Moreover, in most cases, PHP will trigger an error and terminate the program execution. In PHP5, try catch has no way to handle errors.
php7 can capture errors;
1.1 php5 error exception
// 1.异常处理 try{ throw new Exception("Error Processing Request", 1); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 返回: 1 Error Processing Request 158 E:\phpwebenv\PHPTutorial\WWW\test\index.php // 2.结果php错误处理机制 function MyErrorHandler($error,$errstr,$errfile,$errline){ echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>'; echo "Error on line $errline in ".$errfile; } set_error_handler('MyErrorHandler',E_ALL|E_STRICT); try{ // throw new Exception("Error Processing Request", 4); trigger_error('error_msg'); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: Custom error:1024:error_msg Error on line 164 in E:\phpwebenv\PHPTutorial\WWW\test\index.php //3. 处理致命错误:脚本结束后执行 function shutdown_function(){ $e = error_get_last(); echo '<pre/>'; var_dump($e); } register_shutdown_function('shutdown_function'); try{ // throw new Exception("Error Processing Request", 4); // trigger_error('error_msg'); fun(); }catch ( Exception $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: Fatal error: Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\ test\index.php:172 Stack trace: #0 {main} thrown in E:\phpwebenv\PHPTutorial\WWW\test\index.php on line 172 array(4) { ["type"]=> int(1) ["message"]=> string(131) "Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\test\index.php:172 Stack trace: #0 {main} thrown" ["file"]=> string(43) "E:\phpwebenv\PHPTutorial\WWW\test\index.php" ["line"]=> int(172) } 以上方法可以看出,php没有捕获到异常,只能依赖set_error_handler()和register_shutdown_function();来处理,set_error_handler只能接受 异常和非致命的错误。register_shutdown_function():主要针对die()或致命错误,即程序终结后执行;所以php5没有很好的异常处理机制。
1.2 php7 exception handling
// 处理致命错误:脚本结束后执行 function shutdown_function(){ $e = error_get_last(); echo '<pre class="brush:php;toolbar:false">'; var_dump($e); } register_shutdown_function('shutdown_function'); // 结果php错误处理机制 function MyErrorHandler($error,$errstr,$errfile,$errline){ echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>'; echo "Error on line $errline in ".$errfile; } set_error_handler('MyErrorHandler',E_ALL|E_STRICT); try{ // throw new Exception("Error Processing Request", 4); // trigger_error('error_msg'); fun(); }catch ( Error $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; } 结果: 0 Call to undefined function fun() 172 E:\phpwebenv\PHPTutorial\WWW\test\index.php NULL register_shutdown_function();没有捕获到异常
// 2. 如果不用try catch 捕获 function exception_handler( Throwable $e){ echo 'catch Error:'.$e->getCode().':'.$e->getMessage().'<br/>'; } set_exception_handler('exception_handler'); fun();
Summary: Throwable is the base class of Error and Exception. In php7, if you want to catch exceptions, you need to catch errors
try{ fun(); }catch ( Throwable $e){ echo $e->getCode().'<br/>'; echo $e->getMessage().'<br/>'; echo $e->getLine().'<br/>'; echo $e->getFile().'<br/>'; }
3. Error handling of thinkphp5 framework:
在异常错误处理类:Error有这个处理 // 注册错误和异常处理机制 \think\Error::register(); /** * 注册异常处理 * @return void */ public static function register() { error_reporting(E_ALL); set_error_handler([__CLASS__, 'appError']); set_exception_handler([__CLASS__, 'appException']); register_shutdown_function([__CLASS__, 'appShutdown']); } 当程序出现错误时,会执行这些异常、错误的函数;
After connecting to the database, the exception is handled as follows:
/** * 连接数据库方法 * @access public * @param array $config 连接参数 * @param integer $linkNum 连接序号 * @param array|bool $autoConnection 是否自动连接主数据库(用于分布式) * @return PDO * @throws Exception */ public function connect(array $config = [], $linkNum = 0, $autoConnection = false) { if (!isset($this->links[$linkNum])) { if (!$config) { $config = $this->config; } else { $config = array_merge($this->config, $config); } // 连接参数 if (isset($config['params']) && is_array($config['params'])) { $params = $config['params'] + $this->params; } else { $params = $this->params; } // 记录当前字段属性大小写设置 $this->attrCase = $params[PDO::ATTR_CASE]; // 数据返回类型 if (isset($config['result_type'])) { $this->fetchType = $config['result_type']; } try { if (empty($config['dsn'])) { $config['dsn'] = $this->parseDsn($config); } if ($config['debug']) { $startTime = microtime(true); } $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params); if ($config['debug']) { // 记录数据库连接信息 Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql'); } } catch (\PDOException $e) { if ($autoConnection) { Log::record($e->getMessage(), 'error'); return $this->connect($autoConnection, $linkNum); } else { throw $e; } } } return $this->links[$linkNum]; } 当数据库链接失败后,可以重新链接或者直接抛出异常; /** * 析构方法 * @access public */ public function __destruct() { // 释放查询 if ($this->PDOStatement) { $this->free(); } // 关闭连接 $this->close(); } 当执行sql失败后,调用析构方法,关闭数据库链接;
4. When an error occurs in php, the resource is released
php is an explanatory script. Each PHP page is an independent execution program. No matter what method is used, as long as it is executed (including die(), exit(), fatal error termination program), the result will be returned to the server and it will be closed. When the program is closed, the resources will of course be released;
unset(); When multiple variable names or object names point to a storage address, the function of the unset() function is only to destroy the pointers of the variable names and storage addresses. That’s it, when there is only one variable name or object name, unset destroys the content at the specified storage address;
Destruction method: When the instantiated object has no other variables or object names pointing to it, it This method will be executed; or this method will be executed when the object resources are released after the script ends;
Related recommendations:
《The difference in security between PHP7 and PHP5 (example) )》
《Changes brought about by PHP7’s Abstract Syntax Tree (AST)》
《The execution principle of PHP7 language (PHP7 source code analysis )》
《PHP 7.4 is expected to be released in December 2019》
The above is the detailed content of Exception handling mechanism of php5 and php7 (analysis of thinkphp5 exception handling). For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



The differences between php5 and php8 are in terms of performance, language structure, type system, error handling, asynchronous programming, standard library functions and security. Detailed introduction: 1. Performance improvement. Compared with PHP5, PHP8 has a huge improvement in performance. PHP8 introduces a JIT compiler, which can compile and optimize some high-frequency execution codes, thereby improving the running speed; 2. Improved language structure, PHP8 introduces some new language structures and functions. PHP8 supports named parameters, allowing developers to pass parameter names instead of parameter order, etc.

How to install the mongo extension in php7.0: 1. Create the mongodb user group and user; 2. Download the mongodb source code package and place the source code package in the "/usr/local/src/" directory; 3. Enter "src/" directory; 4. Unzip the source code package; 5. Create the mongodb file directory; 6. Copy the files to the "mongodb/" directory; 7. Create the mongodb configuration file and modify the configuration.

To resolve the plugin not showing installed issue in PHP 7.0: Check the plugin configuration and enable the plugin. Restart PHP to apply configuration changes. Check the plugin file permissions to make sure they are correct. Install missing dependencies to ensure the plugin functions properly. If all other steps fail, rebuild PHP. Other possible causes include incompatible plugin versions, loading the wrong version, or PHP configuration issues.

In php5, we can use the fsockopen() function to detect the TCP port. This function can be used to open a network connection and perform some network communication. But in php7, the fsockopen() function may encounter some problems, such as being unable to open the port, unable to connect to the server, etc. In order to solve this problem, we can use the socket_create() function and socket_connect() function to detect the TCP port.

How to change port 80 in php5: 1. Edit the port number in the Apache server configuration file; 2. Edit the PHP configuration file to ensure that PHP works on the new port; 3. Restart the Apache server, and the PHP application will start running on the new port. run on the port.

How to install and deploy php7.0: 1. Go to the PHP official website to download the installation version corresponding to the local system; 2. Extract the downloaded zip file to the specified directory; 3. Open the command line window and go to the "E:\php7" directory Just run the "php -v" command.

Common solutions for PHP server environments include ensuring that the correct PHP version is installed and that relevant files have been copied to the module directory. Disable SELinux temporarily or permanently. Check and configure PHP.ini to ensure that necessary extensions have been added and set up correctly. Start or restart the PHP-FPM service. Check the DNS settings for resolution issues.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...
