gpt4 book ai didi

php - 向 Twig 中的对象添加属性

转载 作者:行者123 更新时间:2023-12-05 02:20:32 24 4
gpt4 key购买 nike

我想将属性 2 添加到 Twig 中的这个对象

object
property1

根据这个问题Updating object properties in twig接受的答案说可以通过合并来实现,但是合并过滤器对对象不起作用,有什么办法可以实现吗?

最佳答案

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

class TestStdClass
{
private $prop1;

public function getProp1()
{
return $this->prop1;
}

public function setProp1($prop1)
{
$this->prop1 = $prop1;
}
}

然后在 Twig 模板中使用标签 do计算表达式(objTestStdClass 的实例):

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

这将打印:

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

关于php - 向 Twig 中的对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38968967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com