We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Using global var in function in view fails

I found something weird, seem like a bug. (Phalcon 1.2.3) Code in a view:


$foo = "Bar";

function a()
{
    global $foo;
    var_dump($foo);
}

var_dump($foo);
a();```
This should show
  string(3) "Bar" string(3) "Bar" 
but shows 
  string(3) "Bar" NULL

This is because $foo is not really a global variable.

View is require()'d from a method and therefore is executed in the context of that method — $foo becomes a local variable. If you want $foo to be global, then you need something like:

global $foo;
$foo = 'Bar';

function a()
{
  global $foo;
  var_dump($foo);
}

var_dump($foo);
a();


3.1k

Thanks, that did the trick.