我对 Twig 有一个问题,(事实上这并不是一个真正的问题,但它让我感到不安)
我在php中有一个Post模型类,并且有一些 protected 变量(我也尝试过私有(private))。为了访问它们,我在 php getMyVariable 中有一个 public 函数。如果在我的 Controller 中我尝试回显 protected 变量,则会出现错误无法访问 protected 属性...
,因此我必须使用该函数来回显我的变量。
这是完全正常的,这就是我想要的
但是,然后我尝试在 Twig 中渲染它,并且我使用与该函数相同的系统来渲染我的变量,它可以工作,很棒......但是如果我尝试直接渲染我的 protected 变量,它也可以工作并且这并不是一个好的做法,有没有办法停止直接在 Twig 中渲染 protected /私有(private)变量(我的意思是超越 getter 函数)
最佳答案
请查看documentation 。 Twig 没有访问 protected 变量,这是不可能的,但由于它的实现,它将改变你的 twig 代码,例如foo.bar
到 $foo.getBar()
并检查该方法是否存在,因此它能够“访问” protected 变量
来自 Twig
的文档
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.
关于php - Twig 访问 protected /私有(private)模型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643007/