Как обработать callback уведомления от чера php
Перейти к содержимому

Как обработать callback уведомления от чера php

  • автор:


Если для события зарегистрирована callback-функция, она будет вызвана когда событие перейдёт в активный статус. Для привязывания функции к событию, необходимо передать её как параметр callable в Event::__construct() или Event::set() или в один из фабричных методов, таких как Event::timer() .

Функция должна соответствовать следующему прототипу:

callback ( mixed $fd = null , int $what = ? , mixed $arg = null ): void

Дескриптор файла, потокового ресурса или сокета, связанный с событием. Для событий сигналов fd совпадает с номером сигнала.

Побитовая маска всех обрабатываемых событий.

Для Event::timer() callback-функция должна соответствовать следующему прототипу:

callback ( mixed $arg = null ): void

Для Event::signal() callback-функция должна соответствовать следующему прототипу:

callback ( int $signum = ? , mixed $arg = null ): void

Номер сигнала (например, SIGTERM ).

Event callbacks

If a callback is registered for an event, it will be called when the event becomes active. To associate a callback with event one can pass a callable to either Event::__construct() , or Event::set() , or one of the factory methods like Event::timer() .

An event callback should match the following prototype:

void callback ([ mixed $fd = NULL [, int $what [, mixed $arg = NULL ]]] )

The file descriptor, stream resource or socket associated with the event. For signal event fd is equal to the signal number.

Bit mask of all events triggered.

User custom data.

Event::timer() expects the callback to match the following prototype:

void callback ([ mixed $arg = NULL ] )

User custom data.

Event::signal() expects the callback to match the following prototype:

void callback ([ int $signum [, mixed $arg = NULL ]] )

The number of the triggered signal(e.g. SIGTERM ).

Callbacks / Callables

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.


A PHP function is passed by its name as a string . Any built-in or user-defined function can be used, except language constructs such as: array() , echo , empty() , eval() , exit() , isset() , list() , print or unset() .

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass ‘ClassName::methodName’.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

Пример #1 Callback function examples

// An example callback function
function my_callback_function () echo ‘hello world!’ ;

// An example callback method
class MyClass static function myCallbackMethod () echo ‘Hello World!’ ;

// Type 1: Simple callback
call_user_func ( ‘my_callback_function’ );

// Type 2: Static class method call
call_user_func (array( ‘MyClass’ , ‘myCallbackMethod’ ));

// Type 3: Object method call
$obj = new MyClass ();
call_user_func (array( $obj , ‘myCallbackMethod’ ));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func ( ‘MyClass::myCallbackMethod’ );

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A public static function who () echo «A\n» ;

class B extends A public static function who () echo «B\n» ;

call_user_func (array( ‘B’ , ‘parent::who’ )); // A

// Type 6: Objects implementing __invoke can be used as callables (since PHP 5.3)
class C public function __invoke ( $name ) echo ‘Hello ‘ , $name , «\n» ;

$c = new C ();
call_user_func ( $c , ‘PHP!’ );

Пример #2 Callback example using a Closure

// This is our range of numbers
$numbers = range ( 1 , 5 );

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map ( $double , $numbers );

print implode ( ‘ ‘ , $new_numbers );

Результат выполнения данного примера:

2 4 6 8 10

Замечание: In PHP 4, it was necessary to use a reference to create a callback that points to the actual object , and not a copy of it. For more details, see References Explained.


Callback-функции, зарегистрированные такими функциями как call_user_func() и call_user_func_array() , не будут вызваны при наличии не пойманного исключения, брошенного в предыдущей callback-функции.

How do I implement a callback in PHP?

The manual uses the terms «callback» and «callable» interchangeably, however, «callback» traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:

$cb1 = 'someGlobalFunction'; $cb2 = ['ClassName', 'someStaticMethod']; $cb3 = [$object, 'somePublicMethod']; // this syntax is callable since PHP 5.2.3 but a string containing it // cannot be called directly $cb2 = 'ClassName::someStaticMethod'; $cb2(); // fatal error // legacy syntax for PHP 4 $cb3 = array(&$object, 'somePublicMethod'); 

This is a safe way to use callable values in general:

if (is_callable($cb2)) < // Autoloading will be invoked to load the class "ClassName" if it's not // yet defined, and PHP will check that the class has a method // "someStaticMethod". Note that is_callable() will NOT verify that the // method can safely be executed in static context. $returnValue = call_user_func($cb2, $arg1, $arg2); >

Modern PHP versions allow the first three formats above to be invoked directly as $cb() . call_user_func and call_user_func_array support all the above.

  1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. [‘Vendor\Package\Foo’, ‘method’]
  2. call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb() ;
  3. Objects with an __invoke() method (including anonymous functions) fall under the category «callable» and can be used the same way, but I personally don’t associate these with the legacy «callback» term.
  4. The legacy create_function() creates a global function and returns its name. It’s a wrapper for eval() and anonymous functions should be used instead.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *