📜 ⬆️ ⬇️

PHP 5.3 programming

You may have heard about the new features that await us in PHP 5.3, but who knows where to use them in real programming? I spent a little time to study them and decided to give a few examples.

Lambda function and closure.


These are anonymous functions that have no significant differences. These functions are more flexible than normal functions and can be written to a variable or defined where they are needed. Using anonymous functions is possible even in pre-5.3 PHP. They can be created using the create_function () function. But it is cumbersome, ugly and unreliable. PHP 5.3 enables us to do this in a more natural and beautiful form.

Lambda function

Examples of using:
<?php<br>$lamda = function() { print “Hello World!”; }<br><br>$lamda();<br><br>call_user_func($lamda);<br>call_user_func_array($lamda,array());<br>?><br><br><?php<br>$list = array(22,4,19,78);<br>usort(<br> $list,<br> function($a,$b){<br> if ($a==$b) return 0;<br> return ($a < $b)?-1:1;<br> }<br>);<br>print_r($list);<br><br>print_r(array_map(<br> function ($sn){ return ($n * $n * $n);},<br> array(1,2,3,4,5,6)<br>));<br>?><br> <br> * This source code was highlighted with Source Code Highlighter .

Closures

Example of use:
<?php
$ string = “Hello World!”;
$closure = function() use ($ string ) {print $ string ; };
$closure();
?>
<?php
function getClosure(){
$ string = “Hello World!”;
return function() use ($ string ) {print $ string ; };
}
$closure = getClosure();
$closure();
?>


* This source code was highlighted with Source Code Highlighter .

Differences between using use () and globals


You can suggest that instead of using () it is better to use globals. Yes, of course, in simple cases of using this or that technique are identical, but there are other cases. Let us imagine that we have a function, and there is a local variable in it. And we want to use this variable in the closure. In this case, we need to use the use () operator. If we used globals, then the closure would look in the $ globals array and would not find our variable. Using use (), a local variable can be used in the body of a closure.

Other uses

And finally


As you can see, the closure and lambda functions are very convenient if you know how to use them. Of course it's a pity that you have to wait a little more before PHP 5.3 comes out. But we must pay tribute to the developers of PHP for much-needed innovations.

')

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


All Articles