Class function as callback php

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.

Passing

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 );
?>

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

Замечание: 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-функции.

Источник

Читайте также:  Проверка на int kotlin

Class function as callback php

Callback-функции как объекты первого класса представлены в PHP 8.1.0 как способ создания анонимных функций из callback-функций. Синтаксис заменяет существующий синтаксис вызова с использованием строк и массивов. Преимущество синтаксиса заключается в том, что он доступен для статического анализа и использует область видимости в точке, где получена callback-функция.

Синтаксис CallableExpr(. ) используется для создания объекта Closure из callback-функции. CallableExpr принимает любое выражение, которое может быть вызвано напрямую в грамматике PHP:

Пример #1 Простой пример callback-функции как объекты первого класса

class Foo public function method () <>
public static function staticmethod () <>
public function __invoke () <>
>
$obj = new Foo ();
$classStr = ‘Foo’ ;
$methodStr = ‘method’ ;
$staticmethodStr = ‘staticmethod’ ;
$f1 = strlen (. );
$f2 = $obj (. ); // вызываемый объект
$f3 = $obj -> method (. );
$f4 = $obj -> $methodStr (. );
$f5 = Foo :: staticmethod (. );
$f6 = $classStr :: $staticmethodStr (. );
// традиционная callback-функция с использованием строки, массива
$f7 = ‘strlen’ (. );
$f8 = [ $obj , ‘method’ ](. );
$f9 = [ Foo ::class, ‘staticmethod’ ](. );
?>

Замечание:

. является частью синтаксиса, а не пропуском.

У CallableExpr(. ) та же семантика, что и у Closure::fromCallable() . То есть, в отличие от callback-функции с использованием строк и массивов, CallableExpr(. ) учитывает область видимости в точке, где она создаётся:

Пример #2 Сравнение области действия CallableExpr(. ) и традиционной callback-функции

class Foo public function getPrivateMethod () return [ $this , ‘privateMethod’ ];
>
private function privateMethod () echo __METHOD__ , «\n» ;
>
>
$foo = new Foo ;
$privateMethod = $foo -> getPrivateMethod ();
$privateMethod ();
// Fatal error: Call to private method Foo::privateMethod() from global scope
// Это потому, что вызов выполняется вне Foo, и с этого момента будет проверяться видимость.
class Foo1 public function getPrivateMethod () // Использует область, в которой получена callback-функция.
return $this -> privateMethod (. ); // идентично Closure::fromCallable([$this, ‘privateMethod’]);
>
private function privateMethod () echo __METHOD__ , «\n» ;
>
>
$foo1 = new Foo1 ;
$privateMethod = $foo1 -> getPrivateMethod ();
$privateMethod (); // Foo1::privateMethod
?>

Замечание:

Создание объекта с помощью этого синтаксиса (например, new Foo(. ) ) не поддерживается, поскольку синтаксис new Foo() не считается callback-функцией.

Замечание:

Callback-функции как объекты первого класса нельзя комбинировать с оператором Nullsafe. Оба следующих результата приводят к ошибке времени компиляции:

Источник

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.

Читайте также:  Все для начинающего вебмастера

Passing

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 );
?>

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

Замечание: 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 to Use Callbacks in PHP

A callback is considered a function reference/object with the type callable.

It can act as an object method, a function, or a static class method.

Here, we will demonstrate the ways of using standard callbacks, static class method callbacks, object method callbacks, as well as closure callbacks.

Читайте также:  Images from pdf python

Using Standard Callbacks

In PHP, you can call functions with the help of the call_user_func() function. The argument is the string name of the function that is going to be called.

 // PHP program to demonstrate work // of a standard callback // Function for printing a string function someFunction( ) < echo "W3docs \n"; > // Standard callback call_user_func('someFunction'); ?>

Using Static Class Method Callback

In PHP, you can call static methods with the help of call_user_func() . Here, the argument is an array that includes the class string name and the method within it to be called.

 // PHP program to demonstrate the working // of a Static class method callback // Sample class class GFG < // Function used for printing a string static function someFunction( ) < echo "Parent W3docs \n"; > > class Article extends GFG < // Function for printing a string static function someFunction( ) < echo "W3docs Article \n"; > > // Static class method callback call_user_func(['Article', 'someFunction']); call_user_func('Article::someFunction'); // Relative Static class method callback call_user_func(['Article', 'parent::someFunction']); ?>
W3docs Article W3docs Article Parent W3docs

Using Object Method Callback

In PHP, you can call object methods with the help of call_user_func() . Here the argument is an array that includes the object variable and the method string name to be called.

Let’s check out an example:

 // PHP program to demonstrate the working // of a object method callback // Sample class class GFG < // Function to print a string static function someFunction( ) < echo "W3docs \n"; > // The __invoke() method is called when a script tries to call an object as a function. public function __invoke( ) < echo "invoke W3docs \n"; > > // Class object $obj = new GFG(); // Object method call call_user_func([$obj, 'someFunction']); // Callable __invoke method object call_user_func($obj); ?>

Closure Callbacks

You can make closure functions callable through standard calls or by mapping the closure function to the array of valid arguments sent to the closure with array_map() . Here, the closure function and the array of its valid arguments are considered the arguments of the function.

The example will look as follows:

 // PHP program to demonstrate the working // of a closure callback // Closure for printing a string $print_function = function ($string) < echo $string . "\n"; >; // Array of strings $string_array = ["Geeksforgeeks", "GFG", "Article"]; // Callable closure array_map($print_function, $string_array); ?>
Geeksforgeeks GFG Article

Using anonymous functions

 // Array of strings $string_array = ["Geeksforgeeks", "GFG", "Article"]; // Callable closure array_map(function($string) < echo $string . "\n"; >, $string_array); ?>
Geeksforgeeks GFG Article

Источник

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