简体   繁体   English

Twig访问受保护/私有模型变量

[英]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) 我在Twig遇到问题,(实际上这不是真正的问题,但它困扰着我)

I have a Post model class in php and i have some protected variables (I also tried with private ). 我在php中有一个Post模型类,并且我有一些受保护的变量(我也尝试过private )。 To acces them I have a public function in php getMyVariable . 要访问它们,我在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. 如果在我的控制器中尝试回显受保护的变量,则会引发错误Cannot access protected property...因此我必须使用该函数来回显我的变量。

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) 但是,然后我尝试在Twig中渲染它,并且我使用了与该函数相同的系统来渲染我的变量,它确实很好,但是...如果我尝试直接渲染我的受保护变量,那么它也可以工作,但这不是确实是一个好习惯, 有没有一种方法可以直接在树枝中停止呈现受保护/私有变量 (我的意思是超越getter函数)

Thanks for your 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, eg foo.bar to $foo.getBar() and check whether that method exists or not, therefor it is able to "access" protected variables Twig没有访问受保护的变量,这是不可能的,但是由于其实现,它将把您的foo.bar代码(例如foo.bar $foo.getBar() foo.bar$foo.getBar()并检查该方法是否存在,因此它能够“访问”受保护的变量


From Twig 's documentation Twig的文档中

For convenience's sake foo.bar does the following things on the PHP layer: 为了方便起见, foo.bar在PHP层上执行以下操作:

 - 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: 另一方面, foo['bar']仅适用于PHP数组:

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

source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM