Forum Moderators: coopster

Message Too Old, No Replies

Nested/includes functions and global

         

bluewolf

2:33 pm on Aug 17, 2007 (gmt 0)

10+ Year Member



Hi, having a slight problem that I've never dealt with and couldn't find anyting when searching the web

I'm not too sure how to explain this, but i'll give it a shot

Basically I have one file with this function:


function foo() {
include("file.php");
}

and in file.php:


$var = "text";
function bar() {
global $var;
echo $var;
}

I've tried using $_GLOBALS as well as globaling $var in foo function but can't seem to get the value of $val in bar

Any ideas? Am I just being stupid? :/

WesleyC

3:02 pm on Aug 17, 2007 (gmt 0)

10+ Year Member



One thing you might try is to convert to using an object-oriented structure instead of simple functions. OOP is much more flexible when it comes to this sort of thing.

[edited by: WesleyC at 3:04 pm (utc) on Aug. 17, 2007]

d40sithui

5:50 pm on Aug 17, 2007 (gmt 0)

10+ Year Member



hmm this is weird.
i tried your script just now.
its weird. i'm unable to call foo().
and since i cant call it, it wont include file.php, which in turn, wont "see" $var, which in turn, well you know the rest
i'm gonna investigate further. interesting problem

d40sithui

6:00 pm on Aug 17, 2007 (gmt 0)

10+ Year Member



ok so even if you run file.php by itself and call bar within it, it still wont show up..

d40sithui

6:11 pm on Aug 17, 2007 (gmt 0)

10+ Year Member



ok so i modified the script a little, and now it wokrs. it must be some kind of php scope thing with using functions to include files... you cant call bar from index.php and it also doest see $var

-------index.php-------
<?
function foo(){
include 'filez.php';
}
foo();
echo $var; //does not work
echo $str; //does not work
bar($var); //does not work
?>

-----filez.php------
<?
$var = "Hello from bar()";
function bar($str){
echo $str;
}
bar($var);
?>

coopster

7:26 pm on Aug 30, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, bluewolf.

$var is not a global variable using the design you have here, it is still "inside" a function, not defined in the global namespace yet. It is easier to see if you actually move the included file into the local script ...

function foo() { 
// include("file.php"); (inserted below)
$var = "text"; // <-- not a global!
function bar() {
global $var;
echo $var;
}
}

Note that $var is not a global variable, it is local in scope to the foo() function. It gets even clearer if you define it in the global scope and run the functions (note, you did not run the functions in your original layout!). Have a look again ...
$var = 'I am a global variable!'; 
function foo() {
//include("file.php");
$var = "text"; // <-- not a global!
function bar() {
global $var;
echo $var;
}
bar();
}
foo();

Prints out
I am a global variable!