note 33726 deleted from function.include-once by sniper
| From: | sniper@php.net | Date: | Tue, 04 Nov 2003 00:43:54 +0000 |
| Subject: | note 33726 deleted from function.include-once by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-59808@lists.php.net to get a copy of this message | ||
Note Submitter: phpContrib (A T) esurfers d o t c o m
----
There is another way to force one-time-only inclusion, it comes from the old C way of handling it
and is very simple. Just add two lines of code at the beginning of your included file:
//----- INCLUDED FILE utils.php
<?php
if(defined('UTILS')) return;
define('UTILS',true);
// all your code to be included only once
// ...
?>
And then you can use simple include()s on it or (of course) you can also use include_once() on it
The UTILS constant can be any constant, and it must be different in every file (using the uppercase
filename without extension is a good habit).
- the file is always read, so it is slower than include_once()
+ it is the included file that "decides" if it is safe or unsafe to be included more than
once. If you modify it (adding a function, for instance) and it becomes unsafe, just add these two
lines of code before the unsafe part instead of converting all your include()s to include_once()
+ you can have half of the file included always, and the other half only once. Just put the two
lines of code in the middle of the file:
<?php
// this will always be included
writeimage($imageName);
if(defined('UTILS')) return; // STOP HERE IF ALREADY INCLUDED
define('UTILS',true);
// function definition will be included only once:
function writeimage($imageName) {
// ...
}
+ you can use it on existing code to switch from include to include-only-once in a safe fast way
+ You can use it as a solution to the case sensitivity problem exposed in Example 12-9 above. Use
include_once() as usual but put the two lines at the beginning of the included file just to be safe
include_once('utils.php');
include_once('Utils.php');
include_once('UTILS.php');
will read the file 3 times (wich is bad), but will include its contents only once (and your code
will work even if someone writes the wrong case).