将属性添加到树枝中的对象

编程入门 行业动态 更新时间:2024-10-27 21:17:35
本文介绍了将属性添加到树枝中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在 twig 中为这个对象添加属性 2

I want to add property 2 to this object in twig

object property1

根据这个问题 更新树枝中的对象属性 接受的答案说它可以通过合并来实现,但是合并过滤器不适用于对象,有什么办法可以实现吗?

According to this question Updating object properties in twig The accepted answer says that it can be achieved by merge, but merge filter does not work with objects, is there any way to achieve this?

推荐答案

我认为最优雅的方法是使用 setter 和 getter:

I think the most elegant way is using setters and getters:

class TestStdClass { private $prop1; public function getProp1() { return $this->prop1; } public function setProp1($prop1) { $this->prop1 = $prop1; } }

然后在 Twig 模板中使用标签 do 计算表达式(obj 是 TestStdClass 的一个实例):

Then in a Twig template use tag do to evaluate expression (obj is an instance of TestStdClass):

{{ dump(obj) }} {# will print an empty object #} {% do obj.setProp1('Hello') %} {{ dump(obj) }}

这将打印:

TestStdClass {#2468 ▼ -prop1: "Hello" }

更多推荐

将属性添加到树枝中的对象

本文发布于:2023-07-17 10:44:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1132396.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:树枝   属性   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!