Twig 访问受保护/私有模型变量 [英] Twig accessing protected/private model variables

查看:67
本文介绍了Twig 访问受保护/私有模型变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Twig 的问题,(实际上这不是一个真正的问题,但它让我感到不安)

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

我在 php 中有一个 Post 模型类,并且我有一些 protected 变量(我也尝试了 private).为了访问它们,我在 php getMyVariable 中有一个 public 函数.如果在我的控制器中我尝试回显受保护的变量,它会给我一个错误 Cannot access protected property... 所以我必须使用该函数来回显我的变量.

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.

这完全正常,这就是我想要的

但是,然后我尝试在 Twig 中渲染它,并且我使用与该函数相同的系统来渲染我的变量,它可以工作,很棒...但是如果我尝试直接渲染我的受保护变量,它也可以工作并且这不是一个很好的做法,有没有办法直接在树枝中停止呈现受保护/私有变量(我的意思是超越getter函数)

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 没有访问受保护的变量,这是不可能的,但是由于它的实现,它将转换您的 twig 代码,例如foo.bar$foo.getBar() 并检查该方法是否存在,因此它能够访问"受保护的变量

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

来自 Twig 的文档

为方便起见 foo.bar 在 PHP 上做了以下事情层:

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'] 另一方面只适用于 PHP 数组:

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.

来源

这篇关于Twig 访问受保护/私有模型变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆