Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include once

Tags:

php

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);
  ...
}

like image 768
Uyghur Lives Matter Avatar asked Apr 07 '10 19:04

Uyghur Lives Matter


People also ask

When to use include or include_once in PHP?

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.

How to avoid including a file more than once in PHP?

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:

How to include a PHP file in another PHP file?

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.

What happens if you include the same function twice in PHP?

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.


2 Answers

"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.

like image 100
selfawaresoup Avatar answered Sep 30 '22 22:09

selfawaresoup


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.

like image 30
hongliang Avatar answered Sep 30 '22 22:09

hongliang