我正在尝试使用数据库中的变量填充模板。数据如下所示:
id field content
1 title New Website
1 heading Welcome!
1 intro This is a new website I have made, feel free to have a look around
2 title About
2 heading Read all about it!
我需要对这些数据做的是设置
$template
的属性对象根据 field
列并将所述值设置为 content
中的内容柱子;例如对于 id = 1$template->title = 'New Website';
$template->heading = 'Welcome!';
$template->intro = 'This is a new websi...';
我有一个数组中的数据,我可以轻松地遍历它,但我无法弄清楚如何让属性成为另一个变量的名称。我尝试了可变变量方法,但无济于事。这是否适用于对象属性?
这是我到目前为止所得到的:
foreach($data as $field)
{
$field_name = $field['field'];
$template->$$field_name = $field['content'];
}
我也试过使用
$template->${$field_name}
和 $template->$$field_name
但到目前为止还没有运气!
最佳答案
$template->{$field_name}
关于php - 如何从变量名动态设置对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3138400/