If I do something like this (it’s just a dummy example, but it will be useful to explain the problem):
variables.php
:
<?php $foo = 'foo'; $bar = 'bar'; ?>
SomeClass.php
:
<?php class SomeClass { public static function do_something() { // XXX Sometimes this works well; but sometimes, // imported variables are null or empty for some // reason within this method's scope require_once( dirname(__FILE__) . '/variables.php' ); echo '<p>foo = '.$foo.'</p>'; echo '<p>bar = '.$bar.'</p>'; } } ?>
Both files are within the same folder; although this class is actually required in scripts that are in other folders.
Most of the time it just prints as expected: foo = foo
and bar = bar
; but when this class is required by some script that does some heavy operations (filling lots of variables in arrays among other stuff, like calculations), it behaves like the imported variables didn’t exist at all (printing foo =
and bar =
).
Looking at apache’s error.log
, the require_once
doesn’t throw any error at all; but it prints something like:
PHP Notice: Undefined variable: foo in /path/to/class_and_variables/SomeClass.php at line 10 PHP Notice: Undefined variable: bar in /path/to/class_and_variables/SomeClass.php at line 11
Normally, it works as expected and the variables are correctly imported within do_something
‘s scope; but with some specific scripts, it doesn’t.
It’s like (I guess) PHP ran out of memory and destroyed the imported variables silently? I don’t know why PHP’s require_once
behaves so strangely sometimes…
Advertisement
Answer
I think this will be only included on the first execution of the method and not on the second one. The second execution of the method will then have the variables not defined. You should use require
instead.