-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
If you render a template with the following code:
{% set hash = {
'foo': 'FOO',
'bar': 'BAR',
} %}
{{ hash[key] }}passing a key variable, set to an instance of an class that defines a __toString() method:
class MyObj {
public function __toString() {
return 'foo';
}
}you will get the error:
Cannot access offset of type MyObj on array
Prior to Twig 3.17, this would have worked when strict_variables was enabled, however it broke in 3.17 due to the change in #4496.
It would be nice if that (string) typecast could be brought back in CoreExtension::getAttribute(), as well as added to GetAttrExpression::compile() for when strict_variables is disabled.
Alternatively, to avoid re-breaking #4476, maybe a helper function could be added somewhere that checks if the passed-in variable is an object with a __toString() method and typecasts it if so; otherwise returns the variable as-is, and CoreExtension::getAttribute() + GetAttrExpression::compile() could wrap the array key in a call to that function.
return $var instanceof Stringable ? (string)$var : $var;