require 'FILE_PATH';
-> file_A.php <?php echo 'Hello there!<br>'; ?> -> file_B.html My name is <b>Mike</b>. -> IncludeExample.php <?php require 'file_A.php'; require '../../file_B.html'; echo "I love PHP!"; ?>
In the above example,Output
Hello there! My name is Mike. I love PHP!
Some of the usage of Require statatements are, 1. Include header's and footer's to pages. 1. Include navigation menu's to pages. 2. Holding variable's that are used across pages. 3. Designing layouts for websites. 4. Including dynamically generated contents. |
include_path = string;
include_path = ".:/dir1/dir2";
include_path = ".;c:\dir1\dir2";
-> file_A.php <?php echo 'Hello there!<br>'; ?> -> IncludeExample2.php <html> <head> <body> <?php require 'fileA.php'; ?> </body> </html>
Output
Hello there!
-> file_A.php <?php echo 'Hello there!<br>'; ?> -> IncludeExample3.php <html> <head> <body> <?php require '../fileA.php'; ?> <?php echo "<br>This will NOT still be printed!!" ?> </body> </html>
A Fatal error is displayed on the Console (or webpage) and the script execution is halted (Note that the echo message after requice statement is not displayed)Output
Warning: include(../fileA.php): failed to open stream: No such file or directory in I:\xampp\htdocs\xampp\Tutorials\IncludeExample3.php on line 5 Fatal error: require(): Failed opening required '../a.php' (include_path='.;I:\xampp\php\PEAR') in I:\xampp\htdocs\xampp\Tutorials\IncludeExample3.php on line 5
include_once should be used when a same file might be included and evaluated more than once during a particular execution of a script. It will help to avoid problems such as function redefinitions, variable value reassignments, etc.
|
-> file_A.php <?php echo 'Hello there!<br>'; ?> -> IncludeExample.php <?php include_once 'file_A.php'; //file_A.php will be included. include_once 'file_A.php'; //As file_A.php is included //above (using include_once) it wont be included again. echo "I love PHP!"; ?>
Note : "Hello there!" is printed only once!Output
Hello there! I love PHP!