Indirect adressing of fields?

I have some fields in my page like

Variable1 : 25
----
Variable2 : 17
----

that would normally adressed like

$page->variable1()
$page->variable2()

What if the field names are only known at runtime? I would like to do some kind of indirect adressing, like

for ($i = 1; $i <= 10; $i++) {
  $varname = "Variable" . $i;
  echo "the fieldname is " . $varname;   // Will output "the fieldname is Variable1"

  $myvalue = $page->$varname();    // that sure will not work
}

I found no such field function in the API, but maybe there is a trick in PHP?

Remeber I have been reading about. From the PHP documentation:

$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

It’s called “Variable functions” but seems not to work inside Kirby.

Yes that is possible

$field = 'variable';
echo $page->{$field . $i}();

Hey that works. Thank you, texnixe.

It is PHP’s concept of “variable variables”. Found the docs right now.

Hello,

I have similar problem
pass 2 vars from the template inside the snippet

template

         <?php 
            snippet('lightbox',
            array('structur_field_name' => 'gallery',
            'collection' => '$page'))
          ?>

snippet

 $image_arr = $collection;
            $structur_field = $structur_field_name;
           
            $image_collection = {$image_arr}->{$structur_field}()->yaml();
            $structurfield_count = {$image_arr}->{$structur_field}()->toStructure()->count();

error output

syntax error, unexpected ‘{’

Hm, you are making things more complicated than they need be by passing one variable to the next. Also, the curly braces around the first variable are not correct, as the error message says:

<?php
$image_collection = $collection->{$structur_field_name}()->yaml();
$structurfield_count = $collection->{$structur_field_name}()->toStructure()->count();
?>

do not work

  $image_collection = $collection->{$structur_field}()->yaml();
            $structurfield_count = $collection->{$structur_field}()->toStructure()->count();

error output
Call to a member function gallery() on string

i tried if ($structur_field)() is the problem but it works.
$page->($structur_field)()->yaml();

and

<?php echo $collection; ?>

output
$page

i found the problem

wrong

 <?php 
            snippet('lightbox',
            array('structur_field_name' => 'gallery',
            'collection' => '$page'))
          ?>

correct

 <?php 
            snippet('lightbox',
            array('structur_field_name' => 'gallery',
            'collection' => $page))
          ?>

thank you @texnixe