Please, consider this code to understand what is going on:
<?php // bar.php
$one = 1;
$two = 2;
and
<?php // foo.php
$someVar = 'var';
function foo()
{
$someOtherVar = 'otherVar';
include 'bar.php';
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
}
foo();
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
will output something like
Array
(
[0] => someOtherVar
[1] => one
[2] => two
)
Array
(
[0] => GLOBALS
[1] => _ENV
[2] => HTTP_ENV_VARS
[3] => argv
[4] => argc
[5] => _POST
[6] => HTTP_POST_VARS
[7] => _GET
[8] => HTTP_GET_VARS
[9] => _COOKIE
[10] => HTTP_COOKIE_VARS
[11] => _SERVER
[12] => HTTP_SERVER_VARS
[13] => _FILES
[14] => HTTP_POST_FILES
[15] => _REQUEST
[16] => someVar
)
As you can see, inside the function scope of foo(), you have access to the vars included in bar.php, but once the function is executed and control flow gets back to the global scope, e.g. after the call to foo() the vars are unavailable, because they have not been exported outside the function scope. If you had included bar.php outside the function scope, e.g.
include 'bar.php'; // instead of foo()
print_r(array_keys(get_defined_vars()));
you'd get
Array
(
...
[16] => someVar
[17] => one
[18] => two
)
Placing a lot of variables into global scope bears the danger of polluting the global scope and risking variable name clashing. That is, one include file might have a $row variable and another might have one too and they overwrite each other. It is better to capsule stuff that belongs together into Classes/Objects and/or substitute the global scope with a Registry pattern.
While I very much favor the OOP approach, you could still do it with your function in place though. Just return the required variable from the function call.
function foo()
{
$someOtherVar = 'otherVar';
include 'bar.php';
// this is why I do not like this approach $one pops out all of a sudden.
// I can deduct, it has to be in bar.php, but if you do that often, your
// code will be very hard to read.
return $one;
}
$user = foo(); // will contain $one then
// get defined vars in current scope
print_r(array_keys(get_defined_vars()));
// gives
Array
(
...
[16] => someVar
[17] => user
)
Of course, if you'd want to have all the variables declared during the call to foo(), you would have to place them into an array, since only one value can be returned at a time. But this is basically when you notice it gets clumsy and switching to classes feels natural (well, at least to me).