What is the advantage of using try() catch() over if() else(). PHP: Anonymous functions Php functions use

Wikipedia says that an anonymous function is a function that can exist without an identifier. Sounds pretty interesting! In this tutorial I will show you some examples of how you can create and call a function using non-standard methods.

Let's start right away with examples:

Function Test($var) ( echo "This is $var"; )

This is a very simple function. Now, in addition to the normal call, we can run this function using a variable that stores the name of this function. Something like this:

$f = "Test"; $f("variable function");

If you run the code, you will see the message This is variable function. Please note that processing single quotes is faster than double quotes.

We can use this technique in OOP as well. Example from php.net:

Class Foo ( function Variable() ( $name = "Bar"; $this->$name(); // This calls the Bar() method ) function Bar() ( echo "This is Bar"; ) ) $foo = new Foo(); $funcname = "Variable"; $foo->$funcname(); // This calls $foo->Variable()

This concept is quite interesting. It can be used to implement callbacks, function tables, and so on.

Now I will try to explain to you what anonymous functions are:

$input = array(1, 2, 3, 4, 5); $output = array_filter($input, function ($v) ( return $v > 2; ));

function ($v) ( return $v > 2; ) is an anonymous function. We can also assign it to a variable to use later.

$max = function ($v) ( return $v > 2; ); $input = array(1, 2, 3, 4, 5); $output = array_filter($input, $max);

Now let's take a look at the new use keyword. Let's write another anonymous function for this (works with PHP 5.3):

$max_comp = function ($max) ( return function ($v) use ($max) ( return $v > $max; ); ); $input = array(1, 2, 3, 4, 5); $output = array_filter($input, $max_comp(2));

In this example we use the snapping effect with keyword use. This technique allows an anonymous function to access external variables. Got a whiff of procedural programming?

Here's another simpler example:

$string = "Hello World!"; $closure = function() use ($string) ( echo $string; ); $closure();

As I already said, the variables that we want to use (from the global scope) in such functions must be passed through use. It's important to note that by default only the value is passed, so if you want to change the contents of the variable being passed and want it to change outside of the anonymous function, pass the value to:

$x = 1; $closure = function() use (&$x) ( ++$x; ); echo $x . "
"; $closure(); echo $x . "
"; $closure(); echo $x . "
";

In this example, our method changes the contents of the $x variable each time the anonymous function is called. If we had not passed the address of the variable, but the variable itself, we would have displayed three 1s.

The real beauty of closure is that it doesn't clutter up the global namespace. As soon as an anonymous function has completed its action, all variables used in it are destroyed automatically.

Closures or anonymous functions in PHP are regular functions but without a name. Let's look at an example of such a function:

This example has an anonymous function, but it doesn't make any sense. The question arises - how to use such functions? The following example will help you understand this:

In this example, we assigned an anonymous function to a variable, then started executing this function using the syntax $closure(); , that is, we added parentheses to the variable name, as when calling a function. Please note that we did not remove the $ sign in the variable name.

But this example is not particularly convenient to use, because you can simple functions use.

How closures are used in practice

Typically anonymous functions or closures in PHP are used to pass them as parameters to another function. PHP has several built-in functions that take a closure as an argument, but this will be discussed below.

Let's make our example even more complicated.

Here we created a regular doStuff() function and passed it our anonymous function from the $closure variable as a parameter, and then ran it in the body of the doStuff() function.

In this example, the doStuff() function is missing a type check for the $closure variable. In order for the doStuff() function to work correctly, the parameter must contain an anonymous function.

is_callable() function

Anonymous functions in PHP are implemented using the built-in Closure class (PHP 5 >= 5.3.0, PHP 7). That is, every anonymous function is an object of this class.

Objects of the Closure class are also called Callbacks/Callables pseudotype. You can check whether a variable belongs to this data type using the is_callable() function.

"; print_r($closure); ) ) $closure = function())( echo "Hello, World!"; ); doStuff($closure); ?>

Note that the gettype function determines the type of the $closure variable to be an object. Therefore, the is_object function will also return true, but this is not an adequate check in our case. The closure needs to be checked using the is_callable function.

use construct

In an anonymous function, you can make a variable from the parent scope visible using the use construct. Here's an example:

Using the use keyword, you can pass several variables to an anonymous function; they are listed in parentheses, separated by commas.

It is also important to understand that the use construct makes visible only variables from the parent scope, and this is not the same as variables from the global scope. The global scope does not change with changes in the execution of functions of varying degrees of nesting.

Arguments in Anonymous Functions

You can pass arguments to an anonymous function. Let's pass one argument to our function as an example.

" . $argument; ); doStuff($closure); ?>

With arguments, everything is very simple; here anonymous functions are no different from ordinary ones.

preg_replace_callback function

I promised several built-in PHP functions that take a closure as an argument, here is one of them: preg_replace_callback

preg_replace_callback - performs a regular expression search and replacement using a callback function (closure).

Preg_replace_callback ($pattern, $callback, $subject)

  • $pattern - the desired pattern, can be either a string or an array of strings.
  • $callback - the callback function to be called, to which an array of matching elements from the subject string will be passed. The callback function should return a string with replacement.
  • $subject - string or array of strings to search and replace.

This is a short syntax; you can read more about the capabilities of this function on the PHP manual website.

More functions that take a closure as an argument: array_filter, array_map, array_reduce, usort.

call_user_func function

Function call_user_func - calls the user function specified in the first parameter. Returns the result of the function, or FALSE on error.

Examples of using call_user_func:

An example of using call_user_func in OOP.

Closure class

As I already wrote, anonymous functions in PHP are implemented using the Closure class. All anonymous functions are objects of this built-in class.

Also note that when calling an object as a function, it is called magic method __invoke (since PHP5.3).

Sum: " . ($variable + $variable_out); ); ) $r = doStuff(); $r(35); doStuff()->__invoke(5);

A function can be assigned to a variable, just like a regular value. To do this, the function name must be assigned to the variable as a string, but without specifying parentheses:

\n"; ) $my_func = "foo"; // Now we can run the foo() function using the $my_func variable, // which stores the name of the specified function as a string $my_func(); // Call the foo() function ?>

Such PHP concept is called “function variables”. It consists in the fact that if you add parentheses to the variable at the end, then PHP interpreter will first check if there is a function with name equal to meaning variable and if such a function exists, it will execute it.

This, as shown in the example above, can only be done with functions by specific users. Built-in language constructs and functions such as echo, unset(), isset() and others cannot be directly assigned to variables in the same way. But you can create your own wrapper function so that built-in language constructs can work like user-defined functions.

Anonymous functions

Anonymous function- a function that does not have its own name; sometimes you can find another name for such functions - lambda function. Anonymous functions can be passed to other functions as arguments or assigned to variables like normal values:

Pay attention to the example, at the end of the function definition there is a semicolon, since an anonymous function is essentially a value, and we assign a value to a variable, then at the end, as for ordinary instructions, a semicolon is placed.

Anonymous functions differ from named functions in that they are created only at the moment when execution reaches them, so they can only be used after they are defined:


Top