开发者

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


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


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.


I always use REQUIRE_ONCE if script contents is unique.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜