Php 如何从变量名动态设置对象的属性?

Php 如何从变量名动态设置对象的属性?,php,oop,Php,Oop,我试图用数据库中的变量填充模板。数据如下: 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! 我需要对该数据做的是根据字段列设

我试图用数据库中的变量填充模板。数据如下:

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
对象的属性,并将所述值设置为
内容
列中的值;e、 g.对于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\u name}
$template->$$field\u name
,但到目前为止没有成功

你超越了自己

$template->{$field_name}
尝试:

为什么这样做有效

$foo = 'bar';
$object->bar = 1;

if ($object->$foo == $object->bar){
   echo "Wow!";
}
使用

或者干脆

$template->$field_name = $field['content'];

为什么我不先试试简单的?!这是
$template->{$field\u name}
但你肯定让我走对了路!
$template->{$field_name} = $field['content'];
$template->$field_name = $field['content'];