views:

412

answers:

4
+3  Q: 

PHP include once.

Is it more efficient to use PHP's include_once or require_once instead of using 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);
  ...
}

+1  A: 

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.

Pickle
A: 

I always use REQUIRE_ONCE if script contents is unique.

SODA
I also almost always use require_once... for a different reason: require_once will give fatal error if the file is missing, while include_once only gives warning in this case. Otherwise, these two are equivalent.
hongliang
+2  A: 

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.

hongliang
You're right. He should have asked if it's faster than: if (!defined('MY_INIT_PHP')) {define('MY_INIT_PHP', true); include 'init.php';}
webbiedave
+3  A: 

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

Techpriester
And the `...defined('MY_INIT_PHP')...` isn't cost-free either. So the performance question would boil down to "is you php-script solution faster than php's internal solution" ...and I doubt that for the vast majority of all cases.
VolkerK
@ VolkerK Yeah, that adds to it, too. Any solution written in interpreted PHP code is by definition slower than PHPs native implementations. At least I can't think of anything different case.
Techpriester