Using variables with strings in with Kirby collection

I’m trying to dynamically generate field names for use in a plugin I’m working on for a project. Kirby returns an Undefined property error whenever I try to use my variable to create a Kirby collection.

$template = $page->template(); $subject = page('constants')->$template.'_subject()';

When I echo $template.'_subject(), it works just fine and shows eg. plots_subject();. When I try to use it to create a Collection ($subject), it returns following error.

Undefined property: Page::$plot_subject().

For some reason, Kirby/PHP tries to cast it to a variable when it should not. Is there a way around this?

Try this:

$template = $page->template();
$field = $template . '_subject';
$subject = $page->$field();
1 Like

Yes! That worked. Thanks :grinning: