EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP Anonymous Function

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP Anonymous Function

PHP Anonymous Function

Introduction to PHP Anonymous Function

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.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

An anonymous function does not carry any name:

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

Different Types of Use Case

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);
?>

Output:

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

PHP Anonymous Function 1

2. Use Case 2

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

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,731 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

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
?>

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 2

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");
?>

Output:

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

inheriting variable from parent scope

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();
?>

Output:

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

PHP Anonymous Function 4

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";
?>

Output:

without using static

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";
?>

Output:

including static

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.

Recommended Articles

This is a guide to PHP Anonymous Function. Here we discuss the introduction and different types of use case. You may also have a look at the following articles to learn more –

  1. PHP Final Class
  2. preg_match in PHP
  3. PHP Tag in HTML
  4. PHP Date Time Functions

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training Course Learn More