php - Twig 访问 protected /私有(private)模型变量

标签 php twig render private protected

我对 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.

source

关于php - Twig 访问 protected /私有(private)模型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643007/

相关文章:

TWIG,动态关联数组 key

php - 无法打开本地文件,但文件在那里

php - 更新 Kartik 网格时隐藏加载程序

javascript - [Wordpress + PHP + MySQL]插件内的数据库SELECT查询没有返回结果

javascript - 从 Twig 中的数组键中删除 ""括号

javascript - 如何使用 React 呈现对象列表

php - 如何使用ajax jquery删除数据表的行

TWIG 和 "unexpected T_FUNCTION"返回 hostmonster.com 的服务器 500 错误

c++ - 使用 VBO 渲染顶点的问题 - OpenGL

grails - 呈现 View ,但gsp中没有对象