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

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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分