![](/img/trans.png)
[英]PHP # Accessing protected or private Variables of class by reference intended or a bug?
[英]Twig accessing protected/private model variables
我在Twig遇到問題,(實際上這不是真正的問題,但它困擾着我)
我在php中有一個Post模型類,並且我有一些受保護的變量(我也嘗試過private )。 要訪問它們,我在php getMyVariable中有一個公共函數。 如果在我的控制器中嘗試回顯受保護的變量,則會引發錯誤Cannot access protected property...
因此我必須使用該函數來回顯我的變量。
這是完全正常的,這就是我想要的
但是,然后我嘗試在Twig中渲染它,並且我使用了與該函數相同的系統來渲染我的變量,它確實很好,但是...如果我嘗試直接渲染我的受保護變量,那么它也可以工作,但這不是確實是一個好習慣, 有沒有一種方法可以直接在樹枝中停止呈現受保護/私有變量 (我的意思是超越getter函數)
感謝您的回答。
請看一下文檔 。 Twig沒有訪問受保護的變量,這是不可能的,但是由於其實現,它將把您的foo.bar
代碼(例如foo.bar
$foo.getBar()
foo.bar
為$foo.getBar()
並檢查該方法是否存在,因此它能夠“訪問”受保護的變量
從Twig
的文檔中
為了方便起見,
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']
僅適用於PHP數組:check if foo is an array and bar a valid element; if not, return a null value.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.