include vs require
Files में code दोबारा इस्तेमाल
बड़े projects code को कई files में बाँटते हैं — header, footer, config, साझा functions। include और require एक file को दूसरी में खींचते हैं ताकि साझा code एक बार लिखें। ये लगभग एक ही काम करते हैं; अंतर तब है जब file न मिले।
include = न मिले तो warning (चलता रहता है); require = fatal error (रुक जाता है)।include
<?php
include "header.php"; // header.php यहाँ खींचता है
echo "Page content";
?>
अगर header.php मौजूद है, उसका code उस बिंदु पर चलता है। न मिले तो PHP warning दिखाती है पर "Page content" तक जारी रहती है। optional हिस्सों के लिए अच्छा।
require
<?php
require "config.php"; // ज़रूरी file
echo "This only runs if config.php loaded";
?>
अगर config.php न मिले, require fatal error देता है और script तुरंत रुक जाती है — echo कभी नहीं चलता। उन files के लिए इस्तेमाल कीजिए जिनकी page को सच में ज़रूरत है।
मुख्य अंतर
| बात | include | require |
|---|---|---|
| File न मिले तो | Warning | Fatal error |
| Script जारी? | हाँ | नहीं, रुक जाती है |
| किसके लिए बढ़िया | Optional हिस्से | ज़रूरी files |
महत्व के आधार पर चुनिए: missing sidebar page न तोड़े (include), पर missing database config सब रोक दे (require)।
include_once और require_once
ये file सिर्फ़ एक बार load करते हैं, line दोबारा चले तब भी।
<?php
require_once "functions.php";
require_once "functions.php"; // दूसरी बार अनदेखा
?>
अगर file functions या classes define करती है, उसे दो बार include करना "cannot redeclare" error देता है। _once versions इसे एक बार load करके रोकते हैं।
आम गलतियाँ
- ज़रूरी files के लिए include इस्तेमाल करना। missing config तब सिर्फ़ warn करता है, और page बाद में confusing तरीके से टूटता है — require इस्तेमाल कीजिए।
- Function files दो बार include करना। "cannot redeclare" देता है;
require_onceइस्तेमाल कीजिए। - गलत file path। Paths मौजूदा script के सापेक्ष हैं — भरोसे को
__DIR__इस्तेमाल कीजिए। - return value की उम्मीद। ये file load करते हैं; value पाने को file से
returnकरवाइए और capture कीजिए।
सारांश
includeऔरrequireएक PHP file को दूसरी में load करते हैं।- Missing file पर
includewarn करके जारी रहता है;requirefatal error से रुक जाता है। - ज़रूरी files को
require, optional हिस्सों कोinclude। require_once/include_oncefile सिर्फ़ एक बार load करते हैं।- भरोसेमंद file paths को
__DIR__इस्तेमाल कीजिए।
आगे, बड़े apps व्यवस्थित कीजिए autoloading से, या code structure कीजिए MVC pattern से।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
include और require में क्या अंतर है?
include सिर्फ़ warning देता है और script चलती रहती है, जबकि require fatal error देकर script रोक देता है। ज़रूरी files के लिए require इस्तेमाल कीजिए।include की जगह require कब इस्तेमाल करूँ?
require जिनके बिना page चल ही नहीं सकता — जैसे database config या core functions। optional हिस्सों के लिए include, जैसे sidebar, जहाँ file न मिलने से पूरा page crash न हो।include_once और require_once क्या करते हैं?
मुझे "cannot redeclare function" error क्यों आता है?
require_once (या include_once) पर switch कीजिए ताकि PHP उसे सिर्फ़ पहली बार load करे।