परिचय
PHP में require_once स्टेटमेंट require स्टेटमेंट के समान कार्य करता है। एकमात्र अंतर यह है कि यदि कोई फ़ाइल पहले से ही प्रोसेसिंग के लिए इन्क्लूड की जा चुकी है, तो इसे फिर से इन्क्लूड नहीं किया जाएगा। ध्यान दें कि include या require स्टेटमेंट के साथ इन्क्लूड की गई फ़ाइल को भी फिर से इन्क्लूड नहीं किया जाएगा भले ही require_once स्टेटमेंट का उपयोग किया जाए।
require_once स्टेटमेंट का अन्य व्यवहार require स्टेटमेंट के समान है।
उदाहरण
उदाहरण 1: require_once के साथ इन्क्लूड
निम्न उदाहरण में मुख्य PHP स्क्रिप्ट test.php को इन्क्लूड करती है:
<?php echo "inside main script\n"; echo "now including with require_once test.php script\n"; require_once "test.php"; echo "try to include it again"; require_once "test.php"; ?> // test.php <?php echo "File included\n"; ?>
आउटपुट
inside main script now including with require_once test.php script File included try to include it again
असफल require_once के लिए त्रुटि
require_once स्टेटमेंट भी घातक त्रुटि का कारण बनता है जब मौजूद न होने वाली फ़ाइल को जोड़ने का प्रयास किया जाता है।
उदाहरण 2: मौजूद न होने वाली फ़ाइल के लिए त्रुटि
<?php echo "inside main script\n"; echo "now including with require_once notest.php script\n"; require_once "notest.php"; ?>
आउटपुट
inside main script now including with require_once notest.php script PHP Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4 Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4