0

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."\n";
}
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.

WeSee
  • 3,158
  • 2
  • 30
  • 58
  • 2
    shouldnt you return `$content` and do `echo l("hello")` ? or just `echo $content` in the function – Muhammad Omer Aslam Mar 16 '19 at 12:46
  • sorry, I corrected the code sample. – WeSee Mar 16 '19 at 12:48
  • i think [this](https://stackoverflow.com/questions/41210784/does-php7-still-support-global-variables) would address your problem as for me in php `5.6` it works correctly – Muhammad Omer Aslam Mar 16 '19 at 12:51
  • not really. Maybe using the supergobal ```$GLOBAL``` could help. But I want to know whats going on here in PHP. Why does the global keyword not help to access ```$content``` in exactely my piece of code? – WeSee Mar 16 '19 at 12:55
  • 1
    Possible duplicate of [Changing a global variable from inside a function PHP](https://stackoverflow.com/questions/4127788/changing-a-global-variable-from-inside-a-function-php) – Skatox Mar 16 '19 at 14:34
  • 1
    I suggest you another solution instead of using global variables, just use \yii\base\View::$params. Here is examples https://stackoverflow.com/a/28039305/3041129 – SiZE Mar 16 '19 at 15:00
  • That could be another solution, indeed. But why is my code not working? – WeSee Mar 16 '19 at 23:07

1 Answers1

1

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."\n";
}
l("hello");
echo "+";
echo $content;
echo "-";

Bingo!

WeSee
  • 3,158
  • 2
  • 30
  • 58