note 23271 deleted from function.require-once by spic
| From: | spic@php.net | Date: | Wed, 28 Aug 2002 08:16:36 +0000 |
| Subject: | note 23271 deleted from function.require-once by spic | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-35864@lists.php.net to get a copy of this message | ||
I just ran into an interesting(?) problem:
I have a small set of PHP scripts that provide dynamic functionality for a specific website. Now,
two of those scripts (let's call them a.php and b.php) may be require'd (or included) by
other scripts or by themselves (e.g. a.php requiring b.php and viceversa).
In my case, I don't want to require the same file more than once, because I would be plagued
with errors telling me that X or Y function is getting redeclared and stuff.
So, I used the require_once function in order to accomplish my task. The problem:
- a.php require_once'd b.php
- b.php require_once'd a.php
When you run some other script, let us say c.php, and it includes a.php or b.php, everything works
fine, but if it's a.php or b.php the file you're trying to run, chances are you will get
redeclaration problems...
Why? well, I guess that's because the file you're running hasn't been
'required' by anyone, technically. So, in my case, when I try to run b.php directly, it
requires a.php, which in turn tries to require b.php, succeeds, and boom.
My solution to the problem was to define a constant on the top of each file, that would help me
identify if the file was already processed or not. Similar to a related technique used in lots of C
header files.
So now my files a.php and b.php look something like:
<?
if (!defined ('_A_PHP')) {
define ('_A_PHP', 1);
/* The contents of a.php */
} // _A_PHP
?>
----
<?
if (!defined ('_B_PHP')) {
define ('_B_PHP', 1);
/* The contents of b.php */
} // _B_PHP
?>
That's it, maybe this would do for an interesting read for someone.