Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
Justin Hileman edited this pageJun 28, 2025 ·2 revisions

Mustache.php supportsPHP magic methods. Specifically, it supports:

  • __toString
  • __isset and__get
  • __invoke

__toString

Whenever an object or value is interpolated in Mustache, it is coerced into a string. This means, if you want to have control over how your object shows up inside{{ myInstance }} tags, you'll want to implement the__toString method.

Note that youmust return a string from__toString. If you return anything else, you'll get anything from an error message in the middle of your template, to a PHP warning, to a full blown meltdown, depending on your current PHP settings.

__isset and__get

These two come in pairs. If you want to use__get magic accessors inside Mustache, youmust implement__isset as well. This is just good practice, in general, but it's essential for Mustache to prevent objects from masking other properties and objects higher on the context stack.

__invoke

Objects which implement__invoke are considered "callable", and can be used as higher-order sections.

Note that__call is missing

Unfortunately, PHP lacks an equivalent to__isset for__call. Short of trying to call a method on an object, there is no way to tell whether it will handle the call. This is fundamentally incompatible with the Mustache context stack. Take this, for example:

{{# foo }}{{ label }}: {{ name }}{{/ foo }}

And the ViewModel:

<?phpclass Foo {public$name;publicfunction__call($method,$args) {return'unknown value';}}

And the data:

<?php$foo =newFoo;$foo->name ='Bob';$tpl->render(['label' =>'name','foo'   =>$foo,]);

This will render as:

unknown value: unknown value

This is because inside the{{# foo }} section, the__call method onFoo would mask the{{ label }} lookup higher in thecontext stack, returningunknown value instead ofname. Because methods win over properties, it would even do the same for Bob's$name property. This is obviously not what you would expect.

The good news is that you can use__isset and__get instead, just like you would normally use__call :)

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp