0

I have a php file that includes another one using include() I defined a variable $something in the included file and that will change depending on a function that runs in the included file.

Now, I want to print that variable in the original file, when I use echo $something it is printing absolutely nothing, help?

user220755
  • 4,358
  • 16
  • 51
  • 68

3 Answers3

9

Let's just leave aside that this is a poor design choice for a moment :)

You're probably running into a issue where you haven't declared the variable as global inside the function which modifies it.

function foo()
{
    global $something;
    $something='bar';
}

You will find the PHP manual page on variable scope most educational in this regard!

So why is this a poor design choice? First of all, check out "Are global variables bad?" which answers the question for C++. The answer is really no different for PHP - it can lead to unmaintainable and unreadable code.

There's another (increasingly historical) wrinkle with PHP though - if the 'register_globals' setting is on, a user can set global variables via the URL query string. This can lead to all manner of security problems, which is why this is now turned off by default (never write new code which requires it to be on).

As a wise man once said, "globals are the path to the dark side. globals lead to anger. anger leads to hate. hate leads to suffering" :)

Community
  • 1
  • 1
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • hopefully, the OP will follow up with, "why is this a poor design choice" in a new question. – Zak Jun 21 '10 at 20:12
  • why is this a poor design choice? (not in a new question but I would like to gain the information, if you don't mind :)) – user220755 Jun 21 '10 at 20:20
  • sorry, I got distracted and intended to expand this answer. Will do a little more on it now! – Paul Dixon Jun 21 '10 at 21:33
1

It is possible you have declared your variable in global scope and are trying to use it in functional scope. To get around this use the global command.

$myglobal = 3;

function printMyGlobal() {
   global $myglobal; // will not work without this line
   echo $myglobal;
}
Fletcher Moore
  • 13,558
  • 11
  • 40
  • 58
0

Use get_defined_vars to debug defined variables