Home > Article > Backend Development > How to create PHP function hooks
In PHP, function hooks are created through the register_shutdown_function() function to execute custom code before and after script execution, which is used for logging, debugging, performance optimization and other scenarios.
How PHP function hooks are created
Function hooks allow you to execute custom code before and after a function is executed. This is useful in scenarios such as logging, debugging, and performance optimization.
In PHP, use the register_shutdown_function()
function to register the hook. It accepts a function name as an argument, which will be called after the script execution is complete.
Grammar:
register_shutdown_function(callable $callback);
Example:
register_shutdown_function(function() { // 脚本执行完成后执行此代码 });
Practical case:
Logging:
register_shutdown_function(function() { // 在脚本执行后将错误日志输出到文件 $log = fopen('errors.log', 'a'); foreach (error_get_last() as $key => $value) { fwrite($log, "{$key}: {$value}\n"); } });
Performance optimization:
register_shutdown_function(function() { // 在脚本执行后打印脚本执行时间 $time = microtime(true) - $GLOBALS['startTime']; printf("\nScript execution time: %.4f seconds\n", $time); });
Notes:
The above is the detailed content of How to create PHP function hooks. For more information, please follow other related articles on the PHP Chinese website!