Reputation: 4446
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?
Upvotes: 0
Views: 151
Reputation: 300825
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" :)
Upvotes: 9
Reputation: 13804
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;
}
Upvotes: 1