Echoing of title() doesn't work


I noticed that

echo $page->title();


echo "<h1>" . $page->title() . "</h1>";

work fine. But

echo "<h1>$page->title()</h1>";

leads to an error message (Undefined property: Page::$title). Could someone explain why the latter code doesn’t work?

Thanks and cheers,

Probably because its a part of a string, and not direct PHP. It doesnt quite know what to do with it.

The best way is like this…

<h1><?= $page->title()->html() ?></h1>

Which is short for:

<h1><?php echo $page->title()->html() ?></h1>

No need to echo the html, or concatenate the html into it… you just want the field content.

1 Like

Why should it work?

You can use a variable within double quotes, but $page->title() is not regarded as a variable.

so this will work:

$title = $page->title();
echo "<h1>$title</h1>";

Or even this:

echo "<h1>{$page->title()}</h1>";

Apart from that, that’s not good coding style.

Stick with:

<h1><?= $page->title()->html() ?></p>
1 Like

Thanks for your answers! I didn’t know that inside of "…" only “pure” variable could be used.

No, I just thought so at first, but according to the PHP docs, you can also use arrays and even object properties (see And as my example above shows, it works if you wrap the function call in curly brackets. But in general, it makes your code less readable. It is good practice to keep the PHP stuff separated from the markup.

1 Like

Normally I’d use the clean variant, but I came across this while generation a whole page in php by loading only snippets without any markup except for the headline, where it seems better to include the HTML tag in the echo string …

Well, with Kirby 3, you can use Kirby’s html helpers:

<?= Html::tag('h1', $page->title()) ?>

With the Kirby 2 you could use bricks. I would still encourage the previous answers.

1 Like