Is it more efficient to use PHP's include_once
or require_once
instead of using a C-like include
with a header guard?
I.e,
include_once 'init.php';
versus
include 'init.php';
//contents of init.php
if (!defined('MY_INIT_PHP')) {
define('MY_INIT_PHP', true);
...
}
When using include or include_once, PHP will throw a warning if the specified file does not exist, but it will not stop the script execution. So, use include only when the specified file is not essential for your program to function correctly.
In the index.php file, if you include the header.php file twice, you’ll see that the page will have two headers: <?php include 'inc/header.php' ?> <?php include 'inc/header.php' ?> <h1> PHP include_once Demo </h1> <?php include 'inc/footer.php' ?> To avoid including a file more than once, you can use the include_once statement:
In this article we will discuss about two more yet useful functions in PHP for file inclusion: include_once () and require_once () functions. The include_once () function can be used to include a PHP file in another one, when you may need to include the called file more than once.
And in the index.php file, you include the functions.php file twice: PHP will issue the following error if you run the index.php file: Fatal error: Cannot redeclare dd () (previously declared in .\inc\functions.php:3) in .\inc\functions.php on line 3 Likewise, if the included file outputs some HTML elements, you’ll see them more once on the page.
"require_once" and "include_once" are generally a bit slower that just "require" and "include" because they perform a check wether the file has already been loaded before.
But the difference only matters in really complex applications where you should do autoloading anyway and by that would not need require_once/include_once, if your autoloader is well coded.
In most simple applications, it's better to use the require_once/include_once for convenience reasons.
The header guard approach is just messy code that should be avoided. Just imagine, if you forgot that check in one of many files. Debugging that could be a nightmare.
Just use autoloading if your application is suitable for it. It's fast and the most convenient and clean way.
I would expect include_once to be faster than using header guard inside the included file, since you still need to open and load the file in the latter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With