- Notifications
You must be signed in to change notification settings - Fork439
Magic methods
Mustache.php supportsPHP magic methods. Specifically, it supports:
__toString__issetand__get__invoke
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.
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.
Objects which implement__invoke are considered "callable", and can be used as higher-order sections.
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 valueThis 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 :)