功能:
register_shutdown_function() 函數可實現當程式執行完成後執行的函數,其功能為可實現程式執行完成的後續操作。程式在運行的時候可能存在執行超時,或強制關閉等情況,但這種情況下默認的提示是非常不友好的,如果使用register_shutdown_function()函數捕獲異常,就能提供更加友好的錯誤展示方式,同時可以實現一些功能的後續操作,如執行完成後的臨時數據清理,包括臨時檔等。
可以這樣理解調用條件:
1、當頁面被用戶強制停止時
2、當程式代碼運行超時時
3、當PHP代碼執行完成時,代碼執行存在異常和錯誤、警告
實例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class ClassDemo { public function __construct() { register_shutdown_function( array ( $this , "f" ), array ( 'bear' =>123, 'ted' => 'test' )); } public function f( $param ) { echo "<pre>f() \$param:" ; print_r( $param ); echo "</pre> "; } public function g( $param ){ echo "<pre>g() \$param:" ; print_r( $param ); echo "</pre> "; } public function h( $param ){ echo "<pre>h() \$param:" ; print_r( $param ); echo "</pre> "; } } $demo = new ClassDemo(); register_shutdown_function( array ( $demo , "g" ), array ( 'bear' =>456, 'ted' => 'test2' )); // register_shutdown_function()函數可重複調用,但執行的順序與註冊的順序相同 echo "before "; exit ; register_shutdown_function( array ( $demo , "h" ), array ( 'bear' =>789, 'ted' => 'test3' )); // 如果在調用register_shutdown_function()函數之前有exit()函數調用,register_shutdown_function()函數將不能執行 echo " after"; |
1 2 3 4 5 6 7 8 9 10 11 12 13 | before f() $param:Array ( [bear] => 123 [ted] => test ) g() $param:Array ( [bear] => 456 [ted] => test2 ) |
注意事項
1,register_shutdown_function()函數可重複調用,但執行的順序與註冊的順序相同
2,如果在調用register_shutdown_function()函數之前有exit()函數調用,register_shutdown_function()函數將不能執行
3,PHP4後支持註冊函數參數傳遞
4,在某些服務端,如Apache,當前目錄在register_shutdown_function()函數中能夠改變
5,register_shutdown_function()函數執行在headers發送之後
應用
來記錄php的輸出日誌
參考資料:
http://my.oschina.net/jiuxiaoyao/blog/78558 利用php的register_shutdown_function来记录php的输出日志
http://yanue.net/post-99.html register_shutdown_function 函数详解
沒有留言:
張貼留言