|
Posted by ECRIA Public Mail Buffer on 10/27/13 11:22
"Andy Hassall" <andy@andyh.co.uk> wrote:
>>Why would you include the same file multiple times in the same file
>>anyway?
> Usually, when you want the output produced by that file printed multiple
> times.
One should never need to include a file more than once in the same script.
In fact, attempting to do so leads to a run-time error! The purpose of
include_once() is not to include a file multiple times, but to PRECLUDE
future inclusions of a file previously included using include() or
include_once(). This is the key point - using include_once() twice with the
same file will NOT run the script in the included file twice - it will
simply ignore the second function call - to prevent the run-time error that
would occur if include() was called more than once.
Functions, a very simple programming concept, were developed to encapsulate
subroutines that may be required several times in a program (or by several
programs, for that matter). If you need to run a subroutine more than
once... use a function.
There are situations when it is necessary to use include_once. For example:
We have a number of different PHP applications. There is certain common
functionality amongst them, or perhaps they have similar dependencies. For
instance, we may include a functions.inc.php file containing helper
functions in several if not all of these applications. We use
include("functions.inc.php") in the main script of each application. Now,
say a situation comes along when we need to use more than one of the
applications on the same site. In fact, they may have been developed with
the intention of being deployed in a mix-and-match manner depending on the
desired solution(s). So, now we have one "super-app", with several smaller
"sub-apps" running under it. We include the functions.inc.php file multiple
times (once in each sub-app), which leads to a run-time error. The solution?
Replace all calls to include() with include_once(). This will ensure that
the functions.inc.php file is NOT included by any of the sub-apps if it has
already been included by another sub-app or the super-app. However, we can
still deploy any single sub-app in a stand-alone environment without
modifying it.
ECRIA
http://www.ecria.com
Navigation:
[Reply to this message]
|