欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

PHP register_shutdown_function()函数的使用示例

时间:2021-01-21 10:56:19|栏目:PHP代码|点击:

通过 register_shutdown_function 方法,可以让我们设置一个当执行关闭时可以被调用的另一个函数。

也就是说,当我们的脚本执行完成或者意外死掉导致 php 执行即将关闭时,我们的这个函数会被调用。

【使用场景】

① 页面被(用户)强制停止

② 程序代码意外终止或超时

③ php4 中没有析构函数,可以使用该函数模拟析构函数

shutdown.php

<?php
header("content-type:text/html;charset=utf-8");
class Shutdown{
  public function endScript(){
    if(error_get_last()){
      echo '<pre>';
      print_r(error_get_last());
      echo '</pre>';
    }
    file_put_contents('D:\practise\php\Error\error.txt', 'this is a test');
    die('脚本结束');
  } 
}

register_shutdown_function(array(new Shutdown(), 'endScript'));

//错误测试
echo md6();

执行,输出:

复制代码 代码如下:

( ! ) Fatal error: Call to undefined function md6() in D:\practise\php\Error\shutdown.php on line 18

 Array
(
    [type] => 1
    [message] => Call to undefined function md6()
    [file] => D:\practise\php\Error\shutdown.php
    [line] => 18
)
脚本结束

复制代码 代码如下:

D:\practise\php\Error\error.txt:
this is a test

注意:register_shutdown_function 方法是从内存中调用的,因此在使用 file_put_contents 方法时,第一个参数一定要使用绝对路径。

上一篇:PHP判断json格式是否正确的实现代码

栏    目:PHP代码

下一篇:php截取utf-8中文字符串乱码的解决方法

本文标题:PHP register_shutdown_function()函数的使用示例

本文地址:http://www.codeinn.net/misctech/48975.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有