Unlike include and include_once, PHP require_once and require are not functions. These are statements or programming constructs. They work in the same way as include and include_once functions.
PHP require_once and require statements are different from include and include_once statements. If the file is successfully included the PHP script executes. If the file with required statement is not available, it generates fatal error and the application is terminated. This is unlike include functions which just generate a warning.
PHP ignores all subsequent require or require_once statements after the first require_once statement. PHP generated fatal error for all subsequent require or require_once statements after the first require statement. Require_once is slightly better in performance than require since after first require_once statement all subsequent require and require_once statements are ignored. You can judge the performance in a large web application and files are included multiple times.
Syntax
require and require_once both need the path and file name as string. The path and file name must be included in single quotes. Path can be absolute or relative.
require ‘path/filename’
require_once ‘path/filename’
PHP require
require statement accepts a file name as string. If the file is located, it is evaluated and included. The functions, variables and constants in the file can now be used in the calling script. If the file is already included, require statement will generate the error.
PHP require_once
The require_once statement works in the same way as require does with one difference. If a file is included with require_once, PHP will simply ignore the next require_once statement. If the mentioned file has not been already been included require_once will include it.
These statements evaluate the file mentioned in the single quotes and copies the scripts of the included file in the calling script where require or require_once statement is used.
Use require statements when you want your application to halt in case include file fails. Use include statements when you want to continue with application even when the file fails to include in calling script.
Example – PHP require_once and require Statements
include.php
<?php function netpay($sal) { return $sal+$sal*.12+$sal*.40-$sal*.09; } ?>
<?php require 'include.php'; ?> <h2> Salary:<?php echo netpay(4000);?></h2> <?php require 'include.php'; ?> <h2> Salary:<?php echo netpay(6000);?></h2> <?php require 'include.php'; ?> <h2> Salary:<?php echo netpay(8000);?></h2>
<?php require_once 'include.php'; ?> <h2> Salary:<?php echo netpay(4000);?></h2> <?php require_once 'include.php'; ?> <h2> Salary:<?php echo netpay(6000);?></h2> <?php require_once 'include.php'; ?> <h2> Salary:<?php echo netpay(8000);?></h2>
Be First to Comment