Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 10 of 13 · PHP Basics & Syntax
Interview question

What are PHP magic constants? PHP मैजिक कॉन्स्टेंट्स क्या हैं?

Answer

Short Answer

Anonymous functions (also known as Closures) are functions that have no name. They are most commonly used as callback parameters for functions like array_map, or assigned directly to variables.

Detailed Explanation & Code Example

Unlike regular functions defined globally with the function keyword and a name, anonymous functions can be created on the fly and passed around like data.


// Assigning an anonymous function to a variable
$greet = function($name) {
    return "Hello, $name";
};

echo $greet("World"); // Output: Hello, World

The use Keyword (Closures)

A massive advantage of anonymous functions in PHP is their ability to inherit variables from the parent scope using the use keyword. This makes them incredibly powerful for data filtering and manipulation.


$multiplier = 3;
$numbers = [1, 2, 3];

// Using a closure to access $multiplier from the parent scope
$multiplied = array_map(function($num) use ($multiplier) {
    return $num * $multiplier;
}, $numbers);

// $multiplied is now [3, 6, 9]

मैजिक कॉन्स्टेंट्स प्रीडिफाइंड कॉन्स्टेंट्स हैं जो इस्तेमाल की जगह के अनुसार बदल जाते हैं। ये डबल अंडरस्कोर में होते हैं।

कॉन्स्टेंटरिटर्न करता है
__LINE__फाइल में वर्तमान लाइन नंबर
__FILE__वर्तमान फाइल का पूरा पाथ
__DIR__वर्तमान फाइल की डायरेक्टरी
__FUNCTION__वर्तमान फंक्शन का नाम
__CLASS__वर्तमान क्लास का नाम
__METHOD__वर्तमान क्लास मेथड का नाम
__NAMESPACE__वर्तमान नेमस्पेस का नाम

इंटरव्यू टिप: एक आम इस्तेमाल है require __DIR__ . '/config.php'; — यह current working directory पर निर्भरता से आने वाली path समस्याओं से बचाता है।

Was this answer clear?