ohmu
ohmu

Reputation: 19780

PHP include once

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

Upvotes: 5

Views: 9028

Answers (4)

selfawaresoup
selfawaresoup

Reputation: 15842

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

Upvotes: 11

hongliang
hongliang

Reputation: 625

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.

Upvotes: 2

mvbl fst
mvbl fst

Reputation: 5263

I always use REQUIRE_ONCE if script contents is unique.

Upvotes: 0

Quasipickle
Quasipickle

Reputation: 4498

You could try it 10,000 times with a timer, but I think defining MY_INIT_PHP is infinitesimally faster.

To be honest, it's likely such a small difference that there's no practical need to care unless you're working for sites like Facebook.

Upvotes: 1

Related Questions