Skip to content
Advertisement

Twig accessing protected/private model variables

I have a problem with Twig, (in fact this is not really a problem but it’s disturbing to me)

I have a Post model class in php and i have some protected variables (I also tried with private). To acces them I have a public function in php getMyVariable. If in my controller I try to echo the protected variable it throz me an error Cannot access protected property... so I have to use the function to echo my variable.

This is totally normal and this is what I want

But, then I try to render it in Twig, and I use the same system with the function to render my variable, it works, great… But if I try to render directly my protected variable, it works too and this is not really a good practice, is there a way to stop rendering protected/private variable directly in twig (I mean outpassing the getter function)

Advertisement

Answer

Please have a look at the documentation. Twig is not accessing the protected variable, which is impossible, but due to its implementation it’s going to transform your twig code, e.g. foo.bar to $foo.getBar() and check whether that method exists or not, therefor it is able to “access” protected variables


From Twig‘s documentation

For convenience’s sake foo.bar does the following things on the PHP layer:

- check if foo is an array and bar a valid element;
- if not, and if foo is an object, check that bar is a valid property;
- if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
- if not, and if foo is an object, check that getBar is a valid method;
- if not, and if foo is an object, check that isBar is a valid method;
- if not, and if foo is an object, check that hasBar is a valid method;
- if not, return a null value.

foo['bar'] on the other hand only works with PHP arrays:

check if foo is an array and bar a valid element;
if not, return a null value.

source

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement