dszpyf4859 2019-03-16 12:39
浏览 319
已采纳

Yii2:视图中的全局变量

I'm need to concatenate lines for later output (markdown processing...). This is why I use a function l() and a global variable $content.

My view code:

$content = "";
function l($line="") {
    global $content;
    $content .= $line."
";
}
l("hello");
echo "+";
echo $content;
echo "-";

outputs

+-

I'd expect:

+Hello-

Why? What am I doing wrong?

I am using PHP 7.2.6

EDIT:

There are several PHP related answers as this one. But they don't help. I suppose the problem is related to Yii2 and more specific to Yii2 view handling.

  • 写回答

1条回答 默认 最新

  • douturan1807 2019-04-05 11:18
    关注

    Found the solution! Crazy!

    Yii2 renders the view inside an object instance.

    This means, the PHP variable declaration

    $content = "";
    

    is not global but local to the rendering context.

    The solution for question is to make the variable declaration in the view global, too:

    global $content = "";
    

    The working code inside the view looks like this now:

    global $content = "";
    function l($line="") {
        global $content;
        $content .= $line."
    ";
    }
    l("hello");
    echo "+";
    echo $content;
    echo "-";
    

    Bingo!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题