Anonymous php function

When I read the questions for Zend Certified PHP Engineer 5.5, I saw a question about anonymous functions, but I need to explain how this works.

function z($x) { return function($y) use ($x) { return str_repeat( $y , $x ); }; } $a = z(2); $b = z(3); echo $a(3).$b(2); 

The output for this code is:

 33222 

But in the function header there is only the parameter $x , from where $y got the value!

+5
source share
4 answers

The z function creates and returns a new function, but anonymous. This new function is defined so that it has one argument - $y . However, this anonymous function also uses the argument $x from function z .

To make it simple, the z function basically creates a function that can repeat any line, but a fixed number of times. The number of repetitions of a line is determined by the value of the argument $x in z .

So, calling z(2) creates a new function functionally equivalent to writing

 function repeat_two_times($y) { return str_repeat($y, 2); } 

In your example, the hard-coded value of 2 is determined by the value of $ x.

You can learn more about this in the documentation . The principle shown in the example can be very useful for creating partial functions , such as add5, inc10, ...

+3
source

First, you initialize the z function:

 $a = z(2); 

$x in the example is set to 2, so the returned function (anonymous function, also called closure) can now be read as (since $x ):

 $a = function($y) { return str_repeat($y, 2); } 

When calling this function:

 echo $a(3); 

You feed this return function with parameter 3 ( $y ).

Output: 33

+2
source

Anonymous features are also known as Closures .

You ask where $y gets its value. The sample code is hard to decrypt, because you use 2s and 3s everywhere. Everything will be clearer if your last lines were

 $a = z(2); $b = z(3); echo $a('A').$b('B'); 

This will lead to:

 AABBB 

But let your code follow. Note that there are two related function calls

  $a = z(2); 

and

  echo $a(3); 

the calling function z() with argument 2 returns a function (which is assigned the name $a ), where the string

  return str_repeat($y, $x); 

in reality:

  return str_repeat($y, 2); 

now you call this function $a() with argument 3. That 3 (the value of $y ) is repeated twice

The same analysis applies to other related function calls:

  $b = z(3); ... echo ... $b(2); 

But in this case 2 is repeated 3 times

+1
source
  function z($x) { return function($y) use ($x) { return str_repeat( $y , $x ); }; } $a = z(2);// here you are setting value of x by 2 $b = z(3);// here you are setting value of x by 3 echo $a(3).$b(2);// here $a(3) 3 is value of y so it becomes str_repeat( 3 , 2 ); which is 33 
0
source

Source: https://habr.com/ru/post/1207731/


All Articles