Php after function call

register_shutdown_function

Регистрирует функцию callback , которая выполнится после завершения работы скрипта или при вызове функции exit() .

Возможна регистрация нескольких подобных функций с помощью register_shutdown_function() , при этом функции будут выполняться в том порядке, в каком они были зарегистрированы. Если вы вызовете exit() в одной из зарегистрированных завершающих функций, процесс будет полностью остановлен и последующие завершающие функции не будут вызваны.

Завершающие функции также могут сами вызывать register_shutdown_function() , чтобы добавить функцию выключения в конец очереди.

Список параметров

Регистрируемая завершающая функция.

Завершающие функции выполняются как часть запроса, поэтому можно отправлять данные на вывод из них и получать доступ к буферизации вывода.

Можно передавать параметры в завершающую функцию, передав дополнительные параметры.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования register_shutdown_function()

function shutdown ()
// Это наша завершающая функция,
// здесь мы можем выполнить все последние операции
// перед тем как скрипт полностью завершится.

echo ‘Скрипт успешно завершился’ , PHP_EOL ;
>

Примечания

Замечание:

Рабочая директория скрипта может измениться внутри завершающей функции на некоторых веб-серверах, например, Apache.

Замечание:

Функции, выполняемые при завершении скрипта, не будут выполнены, если процесс был убит с сигналами SIGTERM или SIGKILL. Хотя вы и не можете перехватить SIGKILL, но вы можете использовать функцию pcntl_signal() , чтобы задать обработчик сигнала SIGTERM, который использует функцию exit() , чтобы завершить скрипт правильно.

Замечание:

Завершающие функции выполняются отдельно от времени, отслеживаемого max_execution_time. Это означает, что даже если процесс будет завершён из-за слишком долгого выполнения, завершающие функции всё равно будут вызваны. Кроме того, если max_execution_time истечёт во время работы завершающей функции, процесс не будет завершён.

Смотрите также

  • auto_append_file
  • exit() — Вывести сообщение и прекратить выполнение текущего скрипта
  • fastcgi_finish_request() — Сбрасывает все запрошенные данные клиенту
  • Раздел Обработка соединений

User Contributed Notes 13 notes

If your script exceeds the maximum execution time, and terminates thusly:

Fatal error: Maximum execution time of 20 seconds exceeded in — on line 12

The registered shutdown functions will still be executed.

I figured it was important that this be made clear!

If you want to do something with files in function, that registered in register_shutdown_function(), use ABSOLUTE paths to files instead of relative. Because when script processing is complete current working directory chages to ServerRoot (see httpd.conf)

A lot of useful services may be delegated to this useful trigger.
It is very effective because it is executed at the end of the script but before any object destruction, so all instantiations are still alive.

Here’s a simple shutdown events manager class which allows to manage either functions or static/dynamic methods, with an indefinite number of arguments without using any reflection, availing on a internal handling through func_get_args() and call_user_func_array() specific functions:

// managing the shutdown callback events:
class shutdownScheduler private $callbacks ; // array to store user callbacks

public function __construct () $this -> callbacks = array();
register_shutdown_function (array( $this , ‘callRegisteredShutdown’ ));
>
public function registerShutdownEvent () $callback = func_get_args ();

if (empty( $callback )) trigger_error ( ‘No callback passed to ‘ . __FUNCTION__ . ‘ method’ , E_USER_ERROR );
return false ;
>
if (! is_callable ( $callback [ 0 ])) trigger_error ( ‘Invalid callback passed to the ‘ . __FUNCTION__ . ‘ method’ , E_USER_ERROR );
return false ;
>
$this -> callbacks [] = $callback ;
return true ;
>
public function callRegisteredShutdown () foreach ( $this -> callbacks as $arguments ) $callback = array_shift ( $arguments );
call_user_func_array ( $callback , $arguments );
>
>
// test methods:
public function dynamicTest () echo ‘_REQUEST array is ‘ . count ( $_REQUEST ). ‘ elements long.
‘ ;
>
public static function staticTest () echo ‘_SERVER array is ‘ . count ( $_SERVER ). ‘ elements long.
‘ ;
>
>
?>

A simple application:

// a generic function
function say ( $a = ‘a generic greeting’ , $b = » ) echo «Saying < $a > < $b >
» ;
>

$scheduler = new shutdownScheduler ();

// schedule a global scope function:
$scheduler -> registerShutdownEvent ( ‘say’ , ‘hello!’ );

// try to schedule a dyamic method:
$scheduler -> registerShutdownEvent (array( $scheduler , ‘dynamicTest’ ));
// try with a static call:
$scheduler -> registerShutdownEvent ( ‘scheduler::staticTest’ );

?>

It is easy to guess how to extend this example in a more complex context in which user defined functions and methods should be handled according to the priority depending on specific variables.

Hope it may help somebody.
Happy coding!

Источник

PHP Callback Functions (Very Simple Examples)

Welcome to a quick tutorial and examples of PHP callback functions. Functions are one of the most basic things that we learn in PHP, then come along with this “callback function” thing… So, just what is a callback?

  • A function that is passed into another function as a parameter.
  • The function is then called inside the other function itself.

Yes, that’s all. Callbacks are actually simple, but yet confusing at the same time. Let us walk through some examples in this guide – Read on!

TLDR – QUICK SLIDES

PHP Callback Function – Simple Example

TABLE OF CONTENTS

CALLBACK FUNCTION EXAMPLES

All right, let us now get into the examples of PHP callback functions.

EXAMPLE 1) CLASSIC CALLBACK FUNCTION

 // (B) PASS FUNKY() INTO CALL_USER_FUNC() call_user_func("funky"); 

First, we have a very simple and classic example here. Remember the two “conditions” of what makes a callback function?

  • Pass a function as a parameter into another function – We pass funky() into call_user_func() as a parameter.
  • The callback function gets called inside the function itself – call_user_func() calls funky() .

For the guys who have not figured out where the name “callback” comes from – We pass funky() into call_user_func() , then call_user_func() calls back to funky() . Get it?

EXAMPLE 2) YET ANOTHER SIMPLE ONE

// (A) FUNCTIONS TO CALL BACK function funkyA () < echo "YO!"; >function funkyB () < echo "MAN!"; >// (B) THE "MAIN" FUNCTION function getFunky ($callback) < if (is_callable($callback)) < $callback(); >> // (C) PASS CALLBACK FUNCTIONS INTO "MAIN FUNCTION" getFunky("funkyA"); getFunky("funkyB");
Оцените статью