Home > Backend Development > PHP Tutorial > PHP Anonymous Function

PHP Anonymous Function

王林
Release: 2024-08-29 12:47:23
Original
574 people have browsed it

The function that can be created without any specific name and used as an input argument in the PHP script, is known as anonymous function. These functions are implemented using Closure class. The process of assigning an anonymous function to a variable is same as any other assignment syntax. By passing a variable from parent scope to the use language construct, an anonymous function from child scope, can inherit the variable.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

An anonymous function does not carry any name:

function($arg1,$arg2,….,$argN){
//The definition for the anonymous function
};
Copy after login

Different Types of Use Cases

There are various objectives which can be achieved by using anonymous function in developing an effective PHP coding. An anonymous function exhibit different functionalities based on different type of use case for which the function is being used.

Five major use cases are given below:

1. Use Case 1

Anonymous function can be used to assign values to variables. It follows same syntax as like other assignment operation.

Example:

The below code snippet is used to assign the given input value to an output value and print the value using the output variable.

Code:

<?php
$Var = function($value) //Anonymous function is used to assign value to variable $Var
{
//Anonymous function definition
printf("The assigned value is: %s\r\n", $value);
};
//Calling the anonymous function using the assigning variable $Var with a string value input
$Var('A string value is assigned');
//Calling the anonymous function using the assigning variable $Var with a integer value input
$Var(35);
?>
Copy after login

Output:

The given input values of type string and integer are printed through the anonymous function call as shown below:

PHP Anonymous Function

2. Use Case 2

The feature of defining anonymous function plays an important role in creating an inline callback function.

In this case the anonymous function can be passed to another function as an input argument.

The below code is written to define a callback function preg_replace_callback.

Having an anonymous function as one of its input paramters.

Code:

<?php
//creating callback function using PHP anonymous function
// preg_replace_callback is the calling function
echo preg_replace_callback('~-([a-z])~', function ($input) {
//Anonymous function definition
return strtoupper($input[1]);
}, 'This is an anonymous callback function!');//End of the definition of the callback function
?>
Copy after login

Output:

On execution of the PHP script, the callback function is triggered and the output from the anonymous function is printed on the output window as shown below:

PHP Anonymous Function

3. Use case 3

Anonymous function can be used to inheriting variable from parent scope.

This use case does not support super global variables, $this variable or any parameter variable having the same name.

Example:

Code:

<?php
$input_text = 'Initial message';
$outputVar = function () {
//Anonymous function definition
var_dump($input_text);
};
$outputVar();
// Inherit the variable $input_text by value
$outputVar = function () use ($input_text) {
var_dump($input_text);
};
$outputVar();
// Inherit the variable $input_text by-reference
$outputVar = function () use (&$input_text) {
var_dump($input_text);
};
$outputVar();
// Modifying the variable value of parent scope from the function call
$input_text = ' Next message';
$outputVar();
// Inserting regular argument along with parent scope variable
$outputVar = function ($arg) use ($input_text) {
var_dump($arg . ' ' . $input_text);
};
$outputVar("Random message");
?>
Copy after login

Output:

The resultant output from the above code is produced as shown below:

PHP Anonymous Function

4. Use case 4

For the PHP version 5.4 onwards, in case of declaration any class, the class is bound to anonymous function feature by default. This makes the variable ‘$this’ available within the scope of any anonymous function defined within the class.

Example:

Code:

<?php
class AnonymousClass
{
public function Classfunction()
{
return function() {
var_dump($this); //Retrieves the dump information of class object using $this variable,once //it is created
};
}
}
$Classobject = new AnonymousClass;
$function = $Classobject->Classfunction();
$function();
?>
Copy after login

Output:

The dump information of the object from the class ‘AnonymousClass’ is printed on the output window as shown below:

PHP Anonymous Function

5. Use case 5

On creation of an object, if a closure is instantiated from the scope of the same object and is registered, it creates a circular reference which results in prevention to immediate destruction of the object. Application of static anonymous function can enable the script to overcome the delay.

The comparative analysis of usage of regular anonymous function and static anonymous function is demonstrated by the below example.

Example:

Case 1: Without using static anonymous function

Code:

<?php
class TrialClass
{
private $AnonymousVar;
public function __construct()
{
$this->AnonymousVar = function () {
};
}
public function __destruct()
{
echo "Destruction function is called";
}
}
new TrialClass;
echo "After the object is being defined";
echo "\n";
?>
Copy after login

Output:

PHP Anonymous Function

Case 2: Including static anonymous function

Code:

<?php
class TrialClass
{
private $AnonymousVar;
public function __construct()
{
$this->closure = self::createClosure();
}
public static function createClosure()
{
return function () {
};
}
public function __destruct()
{
echo "Destruction function is called";
}
}
new TrialClass;
echo "\n";
echo "\n";
echo "After the object is being defined";
echo "\n";
echo "\n";
?>
Copy after login

Output:

PHP Anonymous Function

Additional Note

  • Automatic binding of the current class to anonymous function is default behavior for PHP version 5.4 onwards. This can be prohibited by implementing static anonymous function.
  • It enhances the performance as it can be used to define a function which is meant to be used only once. The anonymous function can be available only for the job that needs to be executed from the function, and does not remain available for the rest of the code.
  • When an anonymous function is used to assign values to variable, PHP takes care of converting the expression into a Closure internal class instance automatically.

The above is the detailed content of PHP Anonymous Function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template