- Lambdas in PHP
- What are Lambdas in PHP and why Should we use them?
- Lambdas Expressions
- Basic PHP Lambda Functions
- Recursive Lambda Functions in PHP
- Lambda Functions in PHP Arrays
- Lambda Function in PHP Classes
- Summary
- Related Results via Envato Market
- Related Content
- Анонимные функции
- Список изменений
- Примечания
Lambdas in PHP
This article is intended to be a guide to lambda functions in PHP. We will learn more about lambda expressions and lambda PHP functions and then we are going step by step through different kinds of examples–from basic lambda functions, recursive lambda functions, lambda functions in PHP arrays and in PHP classes.
What are Lambdas in PHP and why Should we use them?
A lambda is an anonymous function, a function defined with no name that can be stored in a variable and that can be passed as an argument to other functions or methods. In other words, lambda functions are simply throwaway functions that can be defined at any time and are normally attached to a variable. The lambda functions only exist as long as the variables of which they are defined exist, so when that variable goes out of scope, so does the function.
Lambda functions are useful for a number of instances, most notably for many PHP functions that accept a callback function. One such function is array_map(), which allows us to walk through an array and apply a callback function to each element of the array.
Lambdas Expressions
Lambdas expressions are practically the fundamental concept within computer science and mathematics. The lambda calculus consists of a language of lambda terms, which is defined by a certain formal syntax, and a set of transformation rules, which allow manipulation of the lambda terms. The syntax of the lambda calculus defines some expressions as valid lambda calculus expression. An example of lambda expression is factorial F(n), which is also part of this article as a PHP script that uses lambda function, in a below section:
F(n) = 1, if n = 0; else n × F(n − 1) - the computable factorial function
Y := λg.(λx.g (x x)) (λx.g (x x)) - lambda expression of factorial
Basic PHP Lambda Functions
In PHP, lambda functions were introduced from the PHP 4.0.1 version, through the create_function() method, but starting with the PHP 5.3+ version, the lambda function syntax became similar with JavaScipt, so now is a much more readable and convenient way to define a function. The syntax of a lambda function is:
function & (arguments) use (variables)
So, the first PHP application that uses the lambda functions, from this article is a “Hello World example”
You can now see a simple JavaScript lambda function that calculates sum of two numbers and right after it is the PHP lambda function which does the same thing, as I said in the first part of this section they are very similar:
var sum = function(a, b) < return a + b; >alert(sum(15, 2));
Notice that, in the PHP example, the semicolon is mandatory after defining the lambda function:
Next is also a simple example of lambda function that outputs square(15):
Recursive Lambda Functions in PHP
In this section we will create recursive lambda functions as factorial, a sum of a given number of consecutive terms and the Fibonacci function. For creating recursive lambda function we will use Y-combinator. In computer science, a fixed-point combinator is a higher-order function y that satisfies the equation. A combinator is a particular type of higher-order function that may be used in defining functions without using variables. The combinators may be combined to direct values to their correct places in the expression without ever naming them as variables.” You can learn and understand more about Y-combinator < href=”http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator” target=”new”>here.
First application returns a factorial number:
; print 'Factorial='.$factorial( 8 ); ?>
Next application calculates the first n consecutives number sum, in our case 1+2+3+…+23:
return $recursive_sum( $n - 1 ) + $n; >; print 'The recursive sum: 1+2+3+…+23 = '.$recursive_sum(23); ?>
The recursive sum: 1+2+3+…+23 = 276
And the last application from this section is the Fibonacci:
; print 'Fibonacci result is = '.$fibonacci(9); ?>
Lambda Functions in PHP Arrays
As we already said, the lambda functions allow the creation of functions that have no specified name. They are most useful as the value of callbacks parameters, as we will see in this section of this article, but they also have many other purposes. The lambda functions main goal is closely related with the array_map(), array_reduce(), array_filter(), array_walk() and usort() native PHP functions, listed and described below:
- • array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
array array_map (callable$callback , array $array1 [, array $… ] )
- array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value. If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty.
mixed array_reduce ( array $array , callable $callback [,mixed$initial = NULL ] )
- array_filter() iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
array array_filter ( array $array [,callable$callback ] )
- array_walk() applies the user-defined callback function to each element of the array array.
bool array_walk ( array &$array , callable $callback [,mixed$userdata = NULL ] )
bool usort ( array &$array , callable$value_compare_func )
$value) < echo $array[$i].' ; '; >echo '
'; echo 'Listing elements of the array > 21 using array_filter(): '; $output1 = array_filter($array, function ($v) < return $v >21; >); foreach ($output1 as $i => $value) < echo $output1[$i].' ; '; >echo '
'; echo 'Sorting descending the elements from the array using usort(): '; usort($array, function ($a, $b) < return $a < $b; >); foreach ($array as $i => $value) < echo $array[$i].' ; '; >echo '
'; echo 'Listing elements of the array *10 using array_map(): '; $output2 = array_map(function($value) < return $value * 10; >, $array); foreach ($output2 as $i => $value) < echo $output2[$i].' ; '; >echo '
'; echo 'Listing the sum of elements from the array using array_reduce(): '; print_r( array_reduce($array, function ($v1,$v2) < return $v1+$v2 ; >)); echo '
'; echo 'Listing the elements from the array*2 using array_walk(): '; array_walk($array, function(&$value, $i) < if ($value >0) $value *= 2; >); foreach ($array as $i => $value) < echo $array[$i].' ; '; >echo '
'; ?>
Initial array : 21 ; 52 ; 63 ; 94 ; 125 ; 49 ; 351 ; 876 ; 12 ; 3 ; 56 ; Listing elements of the array > 21 using array_filter(): 52 ; 63 ; 94 ; 125 ; 49 ; 351 ; 876 ; 56 ; Sorting descending the elements from the array using usort(): 876 ; 351 ; 125 ; 94 ; 63 ; 56 ; 52 ; 49 ; 21 ; 12 ; 3 ; Listing elements of the array *10 using array_map(): 8760 ; 3510 ; 1250 ; 940 ; 630 ; 560 ; 520 ; 490 ; 210 ; 120 ; 30 ; Listing the sum of elements from the array using array_reduce(): 1702 Listing the elements from the array*2 using array_walk(): 1752 ; 702 ; 250 ; 188 ; 126 ; 112 ; 104 ; 98 ; 42 ; 24 ; 6 ;
Lambda Function in PHP Classes
As you already learned by now, lambda is a function defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects, as you can see in the below examples.
This is a simple “Hello World” example of lambda object:
$B = new Test(); $B->A = function(); call_user_func($B->A); ?>
PHP 5.3 and greater allows calling an object as a lambda function through the magic __invoke() method. The __invoke()method is called when a script tries to call an object as a function.
Below you can see a simple example that shows this:
> $example = new Test(); $example('This is a simple example of lambda function!'); ?>
Outputs: This is a simple example of lambda function!
Summary
This article has explored lambda expressions and lambda PHP functions and you have seen them at work in different PHP examples from basic lambda functions, recursive lambda functions, lambda functions in PHP arrays and PHP classes.
Related Results via Envato Market
Related Content
Анонимные функции
Анонимные функции, также известные как замыкания (closures), позволяют создавать функции, не имеющие определенных имен. Они наиболее полезны в качестве значений callback-параметров, но также могут иметь и множество других применений.
Пример #1 Пример анонимной функции
echo preg_replace_callback ( ‘~-([a-z])~’ , function ( $match ) return strtoupper ( $match [ 1 ]);
>, ‘hello-world’ );
// выведет helloWorld
?>?php
Замыкания также могут быть использованы в качестве значений переменных; 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 ;
?php
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() .