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.

Читайте также:  Сколько времени прошло от даты php

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.
Читайте также:  At symbol php variable

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");
  • We have a “main” getFunky() function that will call back to $callback if specified.
  • So, very straightforward –
    • getFunky(«funkyA») will call back to funkyA() .
    • getFunky(«funkyB») will call back to funkyB() .

    As to why we do this “dumb” way of passing a function into a function, see the following examples.

    EXAMPLE 3) PASS PARAMETERS TO THE CALLBACK FUNCTION

     // (B) CALLBACK FUNCTIONS function twice ($num) < return $num * 2; >function thrice ($num) < return $num * 3; >// (C) RUN! echo repeater(12, "twice"); // 24 echo repeater(12, "thrice"); // 36

    Before the angry trolls scream “this is dumb, we can just call twice(12) directly and it will do the same” – Yes, the whole point of this example is to illustrate:

    • Callback functions are still functions. We can pass variables into callback functions.
    • The idea of using a callback function is to “reuse the main function, but modify the way it acts”. Read the next “practical example” below.

    EXAMPLE 4) CURL FETCH CALLBACK

     > // (B) CALLBACK FUNCTIONS function save ($data) < file_put_contents("demo.html", $data); >function show ($data) < echo $data; >// (C) GO! fetch("https://en.wikipedia.org/wiki/Rule-based_system", "save"); fetch("https://code-boxx.com", "show");
    1. The “main function” fetch() will get content from your specified $url , then passes it into the $after callback function.
    2. We have 2 callback functions here.
      • save() will save the given $data into a file.
      • While show() will directly output $data .

    As you can see, the main process of fetch() is to get content from a website. But depending on the callback function that is passed in, it will act very differently. That is the smart part about callback functions – Reuse a function in different ways.

    EXAMPLE 5) CALLBACK FUNCTION IN CLASS

     > // (B) THE "MAIN" FUNCTION function funky ($callback) < if (is_callable($callback)) < $callback(); >> // (C) PASS STATIC FUNCTION MYFUNC() INTO FUNKY() funky("MyClass::MyFunc");

    Yep, it’s that simple – CLASS::FUNCTION if you ever need to callback a function in a class. But take note that the callback function must be static or PHP will throw an error.

    EXAMPLE 6) CALLBACK FUNCTION IN OBJECT

     > $myObj = new MyClass(); // (B) THE "MAIN" FUNCTION function funky ($callback) < // (B1) FUNCTION IN OBJECT if (is_array($callback)) < call_user_func($callback); >// (B2) "REGULAR" CALLBACK FUNCTIONS else if (is_callable($callback)) < $callback(); >> // (C) PASS OBJECT + FUNCTION TO CALL // SINCE OBJECTS ARE NOT GLOBAL, WE HAVE TO PASS IN ENTIRE OBJECT funky([$myObj, "MyFunc"]);

    Finally, the complication comes when calling a function in an object. Since objects are not global, we have to pass in the entire object along with the callback function.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    QUICK NOTES

    If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for the code, and here are some small extras that may be useful to you.

    INFOGRAPHIC CHEAT SHEET

    THE END

    Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand callback functions, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    Источник

Оцените статью