← Back to PHP Course | Chapter 5: Functions | Lesson 7 of 10

PHP Anonymous Functions

एक anonymous function बिना नाम के एक छोटा helper है, इसे किसी book में publish करने के बजाय किसी को दिए गए एक quick note जैसा। आप इसे एक variable में store कर सकते हैं या इसे इधर-उधर pass कर सकते हैं।
Syntax
php
$closure = function ($parameter) use ($outer_variable) {
    return $parameter;
};

$closure($argument);

एक Anonymous Function क्या है?

एक anonymous function (एक closure) कभी अपना नाम दिए बिना define किया जाता है — बाद में इसे नाम से call करने के बजाय, आप आमतौर पर इसे सीधे एक variable में assign करते हैं या इसे सीधे एक argument की तरह किसी दूसरे function को सौंप देते हैं।

उदाहरण: What is an Anonymous Function?

php
<?php
$greet = function ($name) {
    // Print "Hello, $name!" to the output
    echo "Hello, $name!";
};
$greet("Alice");
?>

Closures को Callbacks की तरह इस्तेमाल करना

array_filter() और usort() जैसे built-in array functions को एक callback चाहिए यह बताने के लिए कि elements को exactly कैसे filter या compare करना है।

Call site पर ही define किया गया एक anonymous function यहाँ एक natural fit है, क्योंकि वह logic आमतौर पर one-off होता है और codebase में कहीं और अपना खुद का नाम नहीं चाहिए।

उदाहरण: Using Closures as Callbacks

php
<?php
// Declare `$numbers` as an array: `[1, 2, 3, 4, 5]`
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function ($n) {
    // Return `$n % 2 === 0` from this function
    return $n % 2 === 0;
});
// Print a human-readable dump of `$even`
print_r($even);
?>

'use' Keyword

use keyword एक closure को उस scope से variables खींचने देता है जिसमें यह define हुआ था — इसके बिना, closure को अपनी parameter list के बाहर की किसी चीज़ तक access नहीं है, उन variables तक भी नहीं जो closure लिखे जाने की जगह पर clearly visible थीं।

उदाहरण: The 'use' Keyword

php
<?php
// Declare `$tax`, set to `0.1`
$tax = 0.1;
$addTax = function ($price) use ($tax) {
    // Return `$price + ($price * $tax)` from this function
    return $price + ($price * $tax);
};
// Print `$addTax(100)` to the output
echo $addTax(100);
?>

Callables को Type Hint करना

किसी parameter के type को callable (या specifically Closure) declare करना document करता है कि एक function को कुछ ऐसा receive करने की उम्मीद है जिसे यह invoke कर सके, और PHP को इसे call site पर enforce करने देता है बजाय सिर्फ तब गलती discover करने के जब function एक non-callable value को call करने की कोशिश करे।

उदाहरण: Type Hinting Callables

php
<?php
// Define the function `apply` taking `callable $fn`, `$value`
function apply(callable $fn, $value) {
    // Return `$fn($value)` from this function
    return $fn($value);
}
// Print `apply(function ($x) { return $x * 2; }, 5)` to the output
echo apply(function ($x) { return $x * 2; }, 5);
?>

Closures और $this

किसी class method के अंदर define किया गया एक closure automatically $this तक access रखता है, उसी object instance को refer करते हुए जिससे enclosing method belong करता है — closure को उस object की properties पढ़ने या modify करने और इसके दूसरे methods call करने देते हुए, exactly वैसे ही जैसे surrounding method कर सकता था।

उदाहरण: Closures and $this

php
<?php
// Define the class `Counter`
class Counter {
    // Declare the private property `$count`, set to `0`
    private $count = 0;
    // Define the function `makeIncrementer` with no parameters
    function makeIncrementer() {
        // Return `function () {` from this function
        return function () {
            $this->count++;
            // Return `$this->count` from this function
            return $this->count;
        };
    }
}
// Create a new `Counter` instance, stored in `$counter`
$counter = new Counter();
// Declare `$increment`, set to `$counter->makeIncrementer()`
$increment = $counter->makeIncrementer();
// Print `$increment()` to the output
echo $increment();
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह उम्मीद करना कि एक closure automatically outer variables देखेगा, जबकि उन्हें use ($var) से import किया जाना ज़रूरी है।
  2. यह उम्मीद करना कि use ($count) outer variable को update कर देगा, जबकि यह एक copy capture करता है; reference के लिए use (&$count) इस्तेमाल करें।
  3. किसी variable को assign किए गए anonymous function के बाद semicolon भूल जाना, जो एक parse error का कारण बनता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.