dongxun3777 2013-03-04 11:40
浏览 141
已采纳

php函数全局定义的变量不适用于Yii

I am having problems with some legacy code that I am trying to add to a Yii project.

It has to do with global variables, which I am well aware should instead be passed as parameters, but since this old code and is used in other projects rewriting it is not really and option.

$testVar = '123';
function testOutput() {
   global $testVar;
   var_dump($testVar);
}
testOutput();

Now if I include this file in a plain php file it works and outputs

string '123' (length=3)

But if I include this file in a Yii controller or even in a template it output this

null

I have tried to search for this issue but I just get a bunch of results about people using global variables incorrectly. I am sure it is not actually a Yii issue but most likely a php_ini setting that Yii is setting, but I can't find anything when searching the code or the Yii docs that would explain this.

This example can be tested by just creating a file with my first code block and then include it into a Yii template or controller. I even tested it with a clean example Yii project.

I hope I didn't hurt my chances of figuring this out by tagging this questiong with Yii since I have a feeling that it is not just a Yii specific issue.

Any insights would be greatly appreciated.

  • 写回答

3条回答 默认 最新

  • duanhan5388 2013-03-04 12:27
    关注

    If you do like this, it will work, I just tested with Yii controller

    global $testVar;
    $testVar = '123';
    function testOutput() {
       global $testVar;
       var_dump($testVar);
    }
    testOutput();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部