PDA

View Full Version : PHP Variable scope w/ Included Functions



Frenchi
July 11th, 2008, 04:45 PM
Hey guys, I've problem for you. I'm running the CLI version of PHP, and having trouble getting my top level variables to be recognized inside of functions defined in external files and brought in via Include();

My code structure is like this:



// This receives operator input as to which mode to enter,
// and include()'s the necessary external file containing
// that mode's functions:
$op_mode = '';
while($op_mode == '') {
fwrite(STDOUT, "Please select operational mode (socket / terminal):\n");
$input = fgets(STDIN);
if(trim($input) == 'socket') {
require $loc."\modules\clientXML.php";
$op_mode = 'socket';
} else if(trim($input) == 'terminal') {
require $loc."\modules\\terminalControl.php";
$op_mode = 'terminal';
}
}
// This calls the main loop function, depending on which
// mode was selected:
$masterActive = true;
while($masterActive) {
if($op_mode == 'socket') {
// Client Commands
parseXML();
} else if($op_mode == 'terminal') {
// Terminal Commands
terminalCommand();
}
}
The functions run properly, they just can't see any variables declared in the main script (i.e. $masterActive). The size of the program makes it infeasible to pass every top-level variable as arguments into the included functions. Is there something I can do to 'un-blind' those included functions?

Frenchi
July 11th, 2008, 05:13 PM
Found a temporary solution by adding the global designator to the individual variable names inside my external functions, like so:



function terminalCommand() {
global $masterActive;
// More code here
}
This gets code within terminalCommand() to recognize $masterActive, but it'll be a fairly extensive process to get all the variables I need into terminalCommand() this way. Other suggestions are most welcome =)

jwilliam
July 11th, 2008, 05:19 PM
As far as I know, everything is working as it should. Function declarations mark the beginning of a new scope and variables outside this scope are not accessible. If they were you'd run into lots of problems. I find that in procedural programs, if you're having to pass a ridiculous amount of variables to a function, you could probably simplify your code a bit... but don't hold me to that as I don't know the nature of you program or what you're trying to do... :)

Frenchi
July 11th, 2008, 05:29 PM
Hm, I guess I've gotten too used to Actionscript, I could've sworn vars declared on the top level were accessible inside functions. Ah well. Thanks for the clarification =)