Global doesn't work


I noticed that within the realm of MODx Rev, ‘global’ takes no effect within a function. i.e.

$foo = 1;

function display_foo() {
global $foo;

echo $foo;


foo() is empty;

(I did check whether it works outside MODX and it does, so it is not a server issue)

Only in case of:

$GLOBALS[‘foo’] = 1;

it works.

How come and is there another way to make the value available?

And by that you mean in snippets?

It’s probably because your snippet code already runs inside a function (and not in the outer most scope).

You could pass it as an argument

$foo = 1;
function display_foo($foo) {
    echo $foo;

or maybe use a closure

$foo = 1;
$display_foo = function () use (&$foo) {
    echo $foo;