Appropriate place to 'include' or 'require' code?
Posted: Thu Jan 06, 2005 12:26 pm
Another newbie question, this perhaps more about style and best practices. Say I have a function xample() that requires support from code that lives in another file, helper.php. I can do this:
where the require_once is inside the function definition, or
putting the require_once first. I've seen examples of both techniques. However, I've noticed a problem with an "internal" include - if the included code declares a global variable, the function won't be able to access it as a global because it was actually declared within the functions own scope.
Example helper.php:
and if I use this:
I don't get The value is XYZZY, I get The value is.
Am I interpreting this right? What are the implications of choosing one over the other? I'm coming from a C/C++ background and this on-the-fly compilation / interpretation stuff is new to me.
Thanks in advance.
Code: Select all
function xample() {
require_once 'helper.php';
echo 'Do something with helper.';
}Code: Select all
require_once 'helper.php';
function xample() {
echo 'Do something with helper.';
}Example helper.php:
Code: Select all
$HELPER = "XYZZY";
function helper_function() {
echo "blah blah";
}Code: Select all
function xample() {
require_once 'helper.php';
global $HELPER;
echo 'The value is $HELPER";
}Am I interpreting this right? What are the implications of choosing one over the other? I'm coming from a C/C++ background and this on-the-fly compilation / interpretation stuff is new to me.
Thanks in advance.