Entry
How do I prevent a file from being included twice?
Is there an equivalent to C's #IFNDEF?
Nov 2nd, 2000 08:14
David Croft, Nathan Wallace, Leon Atkinson,
In PHP4 you can use require_once and include_once, they will only
require/include the file if it hasn't already been included.
Some people use the include() function to include a collection of
functions at the top of each page in their site. If you included files
include still more files, you may be in the situation where a file is
included twice. PHP will not allow you to re-declare a function. In
C, the programmer usually uses #IFNDEF to check that a header file
hasn't been included previously. You can do a similar thing in PHP
using constants. For example:
<?
if(!defined('BUILD_FUNCTIONS_INCLUDED'))
{
define('BUILD_FUNCTIONS_INCLUDED', TRUE);
function build()
{
//function body goes here
}
}
?>
If you want to work at the include file level, rather than the function
level, this method may be more suitable:
<?php // liba.inc
if ( defined( '__LIBA_INC' ) ) return;
define( '__LIBA_INC', 1 );
/*
* Library code here.
*/
?>
This way, the calling scripts don't have to do any of the work. The
shitty thing is that return won't work from require()d files in PHP4
anymore, so require(), for me, has become pretty much superfluous. But
it works in PHP3, so once you get to PHP4, just use include() instead.