'use' कीवर्ड का उपयोग विशिष्ट फ़ंक्शन के स्कोप में वेरिएबल्स को बाइंड करने के लिए किया जा सकता है।
फ़ंक्शन के स्कोप में वेरिएबल्स को बाइंड करने के लिए use कीवर्ड का उपयोग करें:
उदाहरण
<?php
$message = 'hello there';
$example = function () {
var_dump($message);
};
$example();
$example = function () use ($message) { // $message को विरासत में लें
var_dump($message);
};
$example(); // विरासत में मिले वेरिएबल का मान तब से है जब फ़ंक्शन परिभाषित किया गया था, तब नहीं जब कॉल किया गया
$message = 'Inherited value';
$example();
$message = 'reset to hello'; // message रीसेट हो गया
$example = function () use (&$message) { // रेफरेंस द्वारा विरासत में लें
var_dump($message);
};
$example(); // पैरेंट स्कोप में बदला गया मान
// फ़ंक्शन कॉल के अंदर परिलक्षित होता है
$message = 'change reflected in parent scope';
$example();
$example("hello message");
?>
आउटपुट
यह निम्न आउटपुट देगा:
NULL string(11) "hello there" string(11) "hello there" string(14) "reset to hello" string(32) "change reflected in parent scope" string(32) "change reflected in parent scope"
मूल रूप से, 'example' फ़ंक्शन को पहले कॉल किया जाता है। दूसरी बार, $message विरासत में मिला है, और इसका मान तब बदलता है जब फ़ंक्शन परिभाषित किया गया था। $message का मान रीसेट हो जाता है और फिर से विरासत में मिलता है। चूंकि मान रूट/पैरेंट स्कोप में बदल गया था, इसलिए फ़ंक्शन कॉल होने पर परिवर्तन परिलक्षित होते हैं।