I have a PHP class that needs some pre-defined globals before the file is included:
File: includes/Product.inc.php
if (class_exists('Product')) {
return;
}
// This class requires some predefined globals
if ( !isset($gLogger) || !isset($db) || !isset($glob) ) {
return;
}
class Product
{
...
}
The above is included in other PHP files that need to use Product using require_once. Anyone who wants to use Product must however ensure those globals are available, at least that’s the idea.
I recently debugged an issue in a function within the Product class which was caused because $gLogger was null. The code requiring the above Product.inc.php had not bothered to create the $gLogger. So The question is how was this class ever included if $gLogger was null?
I tried to debug the code (xdebug in NetBeans), put a breakpoint at the start of Product.inc.php to find out and every time it came to the if (class_exists(‘Product’)) clause it would simply step in and return thus never getting to the global checks. So how was it ever included the first time?
This is PHP 5.1+ running under MAMP (Apache/MySQL). I don’t have any auto loaders defined.
Thanks for the informative answers guys. My belief was that when you
include a file PHP starts executing it line by line from line one, so
it would not allow me to include the file if the globals were not
defined. I will move the checks into the constructor. Based on the
original question, I accept the answer from @deceze
The file is parsed before it is executed. Classes are “loaded” by parsing, but functions are executed after the parsing. By putting the function call in the same file as the class, the class is always parsed and “loaded” before that function executes, thereby it’s always
true.If you are always including the file using
require_once(which is good), there’s no point in that check anyway. A class definition shouldn’t conditionally depend on some global variables. Rethink what you’re doing here.