Home >Backend Development >PHP Tutorial >How to catch abnormal interruption in PHP

How to catch abnormal interruption in PHP

高洛峰
高洛峰Original
2016-12-09 11:16:181268browse

Foreword

Any programmer may have encountered some mistakes during development, or errors caused by other reasons. Of course, if the user is unwilling or does not follow the constraints of the application, it will also cause some errors when using it. This article mainly introduces the method of using register_shutdown_function for exception handling in PHP. If necessary, you can learn together.

Explanation of detailed examples

For example, to determine whether a script has been executed, you can set an attribute to false and set it to true when the execution is completed. Finally, the method specified by the register_shutdown_function function is used to determine and further exception handling is performed, as shown in the code:

class IndexController extends Controller
{
  /**
   * 脚本执行是否完成
   * @var bool
   */
  protected $complete = false;
  
  public function __construct()
  {
    register_shutdown_function([$this, 'shutdown']);
  }
  
  /**
   * 异常处理
   */
  public function shutdown()
  {
    if ($this->complete === false) {
      dump('www.tanteng.me'); //此处应该输出日志并进行异常处理操作
    }
  }
}

In this way, you can quickly locate whether the script is interrupted, handle exceptions through register_shutdown_function and improve the robustness of the program, and record the status of program interruption, making it easy to quickly locate problems through logs.

register_shutdown_function execution mechanism

PHP transfers the function to be called into memory. This function is called when all PHP statements on the page have been executed. Note that at this time it is called from memory, not from the PHP page, so if there is path information, the absolute path should be used, because PHP has already assumed that the original page does not exist. There is no relative path at all.

You can understand the calling conditions like this:

1. When the page is forced to stop by the user

2. When the program code runs out of time

3. When the PHP code execution is completed


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:vue directive directiveNext article:vue directive directive