Global variables not available in Function

Should this code work in Kirby?
I have the problem that I run a very similar standard PHP application (not Kirby). But within Kirby, the global variables are not passed to the function. Do I need to define them differently somehow?

$pagecount = 1;
$data = null;
$array = null;
$submissions = array();
$meta = null;
$total = null;
$totalcount = 0;
$token = "bla";

function hoppla() {
  global $data, $array, $submissions, $meta, $total, $totalcount, $pagecount, $token;
  … rest of code
};

hoppla();

It works if you define the variables as global before assigning values.

Having said that, the use of global variables is discouraged.

Aren’t they defined as global in my example? If not how do you call the first 8 lines and how do I define global variable?

global $pagecount;
$pagecount = 1;
// ...

function hoppla() {
  global $data, $array, $submissions, $meta, $total, $totalcount, $pagecount, $token;
  … rest of code
};

hoppla();

If you need globally available variable, you’d better define them in your config or an .env file, instead of declaring global variables with global.

This works perfect. But is this Kirby specific to declare them like this? Are unscoped variables of a php code not global for the file by default?

It depends. Many PHP files in a Kirby installation (for sure all templates, snippets, controllers, config, and probably others) do not execute in global scope. Templates for example, very simplified, are run like this by Kirby:

function render($template) {
  $page = page();
  $site = site();
  // other kirby variables
  include $template;
}

render("site/templates/default.php");

The variables you define in “default.php” therefore are executed in the scope of the render function and are not by default global. The named (as in “not anonymous”) functions that you define in “default.php” however get hoisted (stealing from JS nomenclature here for lack of a better word) into global space by PHP.

Therefore, if your example is a template, the situation actually looks more like this:

function render() {
  // ... kirby stuff

  // your stuff:
  $pagecount = 1;
  $data = null;
  $array = null;
  $submissions = array();
  $meta = null;
  $total = null;
  $totalcount = 0;
  $token = "bla";

  function hoppla() {
    global $data, $array, $submissions, $meta, $total, $totalcount, $pagecount, $token;
    … rest of code
  }

  hoppla();
}

render();

After “hoisting”, that would look like this:

function render() {
  // ... kirby stuff

  // your stuff:
  $pagecount = 1;
  $data = null;
  $array = null;
  $submissions = array();
  $meta = null;
  $total = null;
  $totalcount = 0;
  $token = "bla";

  hoppla();
}

function hoppla() {
  global $data, $array, $submissions, $meta, $total, $totalcount, $pagecount, $token;
  … rest of code
}

render();

and that’s why it doesn’t work.

Hey. Thank you very much for this explanation. This completely makes sense. :beer: