Question

guys, if I require a file in a php script, and it's a valid file, will this file be included only once however many times this script is accessed by users, or just included each access but which seems to be a waste of resource? By the way, I use apache2 as server if this matters. And, since there's require_once, why should exist require? Since require_once already did the job of require and won't be re-included. Is there a firm reason for this, I mean in what cases will require be better than require_once?

Was it helpful?

Solution 2

Short answer : think of a PHP script as a program. Your script is run every time a user accesses it, and any included or require(ed) file is loaded every time.

So if 100 users access your PHP page at the same time and that page require(s) another script, then this other script will be loaded 100 times (most likely from the disk cache, so it's not that bad).

As for the difference between require and require_once, RTM. Short version : require_once will make sure that a particular file is require(d) only once during the life span of your script (this is most useful to prevent loops of includes), while require will allow you to include the same snippet of code at multiple places in your script (for example to add the same ad-banner on top and bottom of your page).

There are caching mechanisms (like memcached) that can help to reduce the waste of resources (but not in the manner you'd expect from your question).

OTHER TIPS

For better understanding read well these

The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

http://php.net/manual/en/function.require-once.php

Require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

http://www.php.net/manual/en/function.require.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top