How to reference $page within filter function

When calling ->filter(function(… how can I reference the actual $page variable within the function ?

Using $page directly returns undefined, I assume because of PHP scope, which would be solved by passing the var as argument to the function… but how to do it in this case? this wild guess…

<?php $myVar = $page->children()->filter(function ($child, $page) {
  return ....

…does not work, I get “Too few arguments to function Kirby\Toolkit\Tpl::{closure}(), 1 passed and exactly 2 expected”

Thank you

In your example, you can get around this limitation in PHP by using the $child->parent() method inside the closure.

$myVar = $page->children()->filter(function ($child) {
  $p = $child->parent();

  return ....

There are cases in which you really need to use a variable from the outer scope inside a closure. In those instances, the use keyword does the trick.

$myVar = $page->children()->filter(function ($child) use ($page) {
  return ....

Ah , but of course, I forgot about ‘use’

Thank you very much