$page, $site... scope in nested code

Hello,

When I attempt to use $site, or $page, deep within some nested code, I get ‘undefined variable’. Something like this in home template:

function myf($arr){
  if($this == $that){
    foreach($arr as $i){
      if($those < $these){
        echo $site->... / $page->...
 ...

I would like to understand why, as I would expect these to be always available.

This is probably a php/kirby basic, It would be great if someone could please explain.

For context, I am writing a function that walks a page’s children and subchildren recursively, in order to give them some attributes that allows me to position their titles on the page in a manner a bit different that would be natural to the tree.

Thanks!

You can do this:

function test() {
  echo site()->title();
}

test();

but not

function test() {
  echo $site->title();
}

test();

Thank you @texnixe, would you mind explain why is this, please? Or could you link me to where this is explained?

thanks!

The problem is not the nesting within you function but scope. The $site and $page variables are only known within the page context but not within your custom function. Variables used within a function are local variables in PHP, so you would have to define them first. What is available, are the helper functions mentioned above, an alternative would be to pass these objects as parameters when you call the function.


function test($page, $site) {
  echo $site->title() . ' | ' . $page->title();
}

test($page, $site); //result (in Starterkit, home.php): Kirby Starterkit | Home

Thank you, that helps.