What are PHP magic constants? PHP मैजिक कॉन्स्टेंट्स क्या हैं?
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?