Php anonymous functions this

PHP Anonymous Functions

Summary: in this tutorial, you will learn about PHP anonymous functions and how to use them effectively.

Introduction to anonymous functions

When you define a function, you specify a name for it. Later, you can call the function by its name.

For example, to define a function that multiplies two numbers, you can do it as follows:

 function multiply($x, $y) < return $x * $y; >Code language: HTML, XML (xml)

The multiply() function accepts two arguments and returns the result. To call the multiply() function, you pass the arguments to it like this:

 multiply(10, 20);Code language: HTML, XML (xml)

In this example, the multiply() is a named function. And you can reuse it as many times as you want.

Besides named functions, PHP allows you to define anonymous functions.

An anonymous function is a function that doesn’t have a name.

The following example defines an anonymous function that multiplies two numbers:

 function ($x, $y) < return $x * $y; >;Code language: HTML, XML (xml)

Since the function doesn’t have a name, you need to end it with a semicolon ( ; ) because PHP treats it as an expression.

This anonymous function is not useful at all because you cannot use it like a named function.

To use an anonymous function, you need to assign it to a variable and call the function via the variable.

The following example assigns the anonymous function to the $multiply variable:

 // . $multiply = function ($x, $y) < return $x * $y; >;Code language: HTML, XML (xml)

And this calls the anonymous function via the $multiply variable:

echo $multiply(10, 20);Code language: PHP (php)

When you dump the information of the $multiply variable, you’ll see that it’s actually a Clousure object:

object(Closure)#1 (1) ["parameter"]=> array(2) < ["$x"]=>string(10) "" ["$y"]=>string(10) "" > >Code language: PHP (php)

Note that the Closure in PHP is not the same as the closure in other programming languages such as JavaScript or Python.

Since an anonymous function is an object, you can assign it to a variable, pass it to a function, and return it from a function.

Passing an anonymous function to another function

PHP has many built-in functions that accept a callback function, for example, the array_map() function.

The array_map() function accepts a callback function and an array. It applies the callback function to each element and includes the results in a new array.

The following example shows how to double each number in an array:

 function double_it($element) < return $element * 2; > $list = [10, 20, 30]; $double_list = array_map(double_it, $list); print_r($double_list);Code language: HTML, XML (xml)
  • First, define a named function called double_it to double a number.
  • Second, define an array of integers.
  • Third, call the array_map() function to double each element of the $list array.
  • Finally, show the result array.
Array ( [0] => 20 [1] => 40 [2] => 60 )Code language: PHP (php)

This example works perfectly fine. However, it’s quite verbose. And the double_it function may be used once.

The following example does the same but uses an anonymous function instead:

 $list = [10, 20, 30]; $results = array_map(function ($element) < return $element * 2; >, $list); print_r($results);Code language: HTML, XML (xml)

Scope of the anonymous function

By default, an anonymous function cannot access the variables from its parent scope. For example:

 $message = 'Hi'; $say = function () < echo $message; >; $say(); Code language: HTML, XML (xml)

PHP issued the following notice:

PHP Notice: Undefined variable: message in . Code language: plaintext (plaintext)

In this example, the anonymous function attempts to access the $message variable from its parent scope. However, it could not. Therefore, PHP issued a notice.

To use the variables from the parent scope inside an anonymous function, you place the variables in the use construct as follows:

 $message = 'Hi'; $say = function () use ($message) < echo $message; >; $say();Code language: HTML, XML (xml)

Now, it should work correctly.

Note that the $message is passed to the anonymous function by value, not by reference. If you change it inside the anonymous function, the change will not reflect outside of the function. For example:

 $message = 'Hi'; $say = function () use ($message) < $message = 'Hello'; echo $message; >; $say(); echo $message;Code language: HTML, XML (xml)

In this example, inside the anonymous function the value of the $message is ‘Hello’ . However, outside of the anonymous function, the value of the message remains the same as ‘Hi’ .

If you want to pass a variable to an anonymous function by reference, you need to use the & operator like the following example:

 $message = 'Hi'; $say = function () use ($message) < $message = 'Hello'; echo $message; >; $say(); echo $message; Code language: HTML, XML (xml)

Now, you see the ‘Hello’ messages twice.

Return an anonymous function from a function

The following example illustrates how to return an anonymous function from a function:

 function multiplier($x) < return function ($y) use ($x) < return $x * $y; >; > $double = multiplier(2); echo $double(100); // 200 $tripple = multiplier(3); echo $tripple(100); // 300Code language: HTML, XML (xml)
  • First, define a function called mutiplier that returns an anonymous function.
  • Second, call the multiplier function and assign its returned value to the $double variable. Since the return value is a function, it can be invoked like a regular function ( $double(2) ).
  • Third, call the multiplier function and assign its returned value to the $tripple variable. This time we passed 3 instead of 2.

Summary

  • An anonymous function is a function without a name.
  • An anonymous function is a Closure object.
  • To access the variables from the parent scope inside an anonymous function, place the variables in the use construct.
  • An anonymous function can be assigned to a variable, passed to a function, or returned from a function.

Источник

Php anonymous functions this

In the previous article, we have learned the use of anonymous functions, and the small partners who have not seen them can enter the delivery door first to understand the use of the closing package anonymous function, transfer:I still don’t know if PHP has a closure? Then you really have OUT.。

About closing anonymous functions, there is a typical issue in JS to bind a THIS scope. In fact, this problem also exists in PHP, such as the following code:

$func = function($say)< echo $this->name, ':', $say, PHP_EOL; >; $func('good'); // Fatal error: Uncaught Error: Using $this when not in object context 

In this anonymous function, we use \ $ this-> name to get the $ Name property from the current scope, but who is this $ this? We did not define it, so it will be reported directly here. The error message is: Using $ this but there is no object context, that is, the scope of the $ THIS reference is not specified.

Bind $ this binding $ THIS

Ok, then we give it a scope, like JS, use a bindto () method.

$func1 = $func->bindTo($lily, 'Lily'); // $func1 = $func->bindTo($lily, Lily::class); // $func1 = $func->bindTo($lily, $lily); $func1('cool'); 

This will output it normally. The bindto () method is to copy a current closing object and then give it a $ THIS scope and class scope. Among them, the $ LILY parameter is an Object $ NewTHIS parameter, which is to specify $ THIS to this copy. The second parameter ‘lily’ is bound to a new type of scope, which represents a type, which determines which private and protected methods can be called in this anonymous function, and the three methods given in the above example Can be used to define this parameter. If you don’t give this parameter, then we can’t access this Private $ Name property:

$func2 = $func->bindTo($lily); $func2('cool2'); // Fatal error: Uncaught Error: Cannot access private property Lily::$name 

Call () method Bind $ this

After PHP7, PHP adds a call () method to $ this binding of anonymous functions, let’s see what differences in it and bindto () methods.

$func->call($lily, 'well'); // Lily:well 

Is it convenient to feel more. First, it executes directly, it doesn’t need to be assigned to a variable, that is, it is not to copy the closure function but directly; secondly, there is no type of scope, the first parameter is still specified The new $ this point, while the back parameters are the parameters of the original closure function.

Although it is very convenient, it also brought another problem because there is no limit to the domain, so it will undermine the package. Hello to do a good job-oriented design, encapsulate a bunch of properties, then use this call () to expose all private and protected content of the object. Of course, this is also to see our own business situation. After all, we can choose freely when writing code.

to sum up

In fact, including closing functions, these features are very similar to JS. This is also a trend of language integration. Whether it is learning JS to see these features of PHP or learn PHP and then go to see JS, which will make us more easily understand their role and ability, this is the convergence of language characteristics benefit. No matter what, learning is, let’s keep! !

Источник

Анонимные функции

Анонимные функции, также известные как замыкания (closures), позволяют создавать функции, не имеющие определенных имен. Они наиболее полезны в качестве значений callback-параметров, но также могут иметь и множество других применений.

Пример #1 Пример анонимной функции

echo preg_replace_callback ( ‘~-([a-z])~’ , function ( $match ) return strtoupper ( $match [ 1 ]);
>, ‘hello-world’ );
// выведет helloWorld
?>

Замыкания также могут быть использованы в качестве значений переменных; PHP автоматически преобразует такие выражения в экземпляры внутреннего класса Closure. Присвоение замыкания переменной использует тот же синтаксис, что и для любого другого присвоения, включая завершающую точку с запятой:

Пример #2 Пример присвоения анонимной функции переменной

Замыкания могут также наследовать переменные из родительской области видимости. Любая подобная переменная должна быть объявлена в конструкции use.

Пример #3 Наследование переменных из родительской области видимости

// Без «use»
$example = function () var_dump ( $message );
>;
echo $example ();

// Наследуем $message
$example = function () use ( $message ) var_dump ( $message );
>;
echo $example ();

// Значение унаследованной переменной задано там, где функция определена,
// но не там, где вызвана
$message = ‘world’ ;
echo $example ();

// Сбросим message
$message = ‘hello’ ;

// Измененное в родительской области видимости значение
// остается тем же внутри вызова функции
$message = ‘world’ ;
echo $example ();

// Замыкания могут принимать обычные аргументы
$example = function ( $arg ) use ( $message ) var_dump ( $arg . ‘ ‘ . $message );
>;
$example ( «hello» );
?>

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

Notice: Undefined variable: message in /example.php on line 6 NULL string(5) "hello" string(5) "hello" string(5) "hello" string(5) "world" string(11) "hello world"

Наследование переменных из родительской области видимости не то же самое, что использование глобальных переменных. Глобальные переменные существуют в глобальной области видимости, которая не меняется, вне зависимости от того, какая функция выполняется в данный момент. Родительская область видимости — это функция, в которой было объявлено замыкание (не обязательно та же самая, из которой оно было вызвано). Смотрите следующий пример:

Пример #4 Замыкания и область видимости

// Базовая корзина покупок, содержащая список добавленных
// продуктов и количество каждого продукта. Включает метод,
// вычисляющий общую цену элементов корзины с помощью
// callback-замыкания.
class Cart
const PRICE_BUTTER = 1.00 ;
const PRICE_MILK = 3.00 ;
const PRICE_EGGS = 6.95 ;

protected $products = array();

public function add ( $product , $quantity )
$this -> products [ $product ] = $quantity ;
>

public function getQuantity ( $product )
return isset( $this -> products [ $product ]) ? $this -> products [ $product ] :
FALSE ;
>

public function getTotal ( $tax )
$total = 0.00 ;

array_walk ( $this -> products , $callback );
return round ( $total , 2 );
>
>

// Добавляем несколько элементов в корзину
$my_cart -> add ( ‘butter’ , 1 );
$my_cart -> add ( ‘milk’ , 3 );
$my_cart -> add ( ‘eggs’ , 6 );

// Выводим общую сумму с 5% налогом на продажу.
print $my_cart -> getTotal ( 0.05 ) . «\n» ;
// Результатом будет 54.29
?>

Список изменений

Версия Описание
5.4.0 Стало возможным использовать $this в анонимных функциях.
5.3.0 Появление анонимных функций.

Примечания

Замечание: Совместно с замыканиями можно использовать функции func_num_args() , func_get_arg() и func_get_args() .

Источник

Читайте также:  Вопросы на экзамен css
Оцените статью