note 33726 added to function.include-once

From: Date: Sat, 05 Jul 2003 11:01:41 +0000
Subject: note 33726 added to function.include-once
Groups: php.notes 
Request: Send a blank email to php-notes+get-51550@lists.php.net to get a copy of this message
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). ---- Manual Page -- http://www.php.net/manual/en/function.include-once.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33726 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33726&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33726&report=yes

« previous php.notes (#51550) next »