开发者

Retrieving variables from included files

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 开发者_JAVA百科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?


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" :)


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;
}


Use get_defined_vars to debug defined variables

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜