Matt
Matt

Reputation: 9433

How to set properties of an object dynamically, from a variable name?

I'm trying to populate a template with variables from a database. The data looks as follows:

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!

What I need to do with that data is set properties of a $template object according to the field column and set said values to what's in the content column; e.g. for id = 1

$template->title = 'New Website';
$template->heading = 'Welcome!';
$template->intro = 'This is a new websi...';

I have the data in an array and I can easily loop over it but I just can't figure out how to get the properties to be the names of another variable. I've tried the variable variables approach but to no avail. Does that work with object properties?

Here's what I've got so far:

foreach($data as $field)
{
    $field_name = $field['field'];
    $template->$$field_name = $field['content'];
}

I've also tried using $template->${$field_name} and $template->$$field_name but so far no luck!

Upvotes: 4

Views: 8566

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

$template->{$field_name}

Upvotes: 14

oezi
oezi

Reputation: 51807

use

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

or simply

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

Upvotes: 2

timdev
timdev

Reputation: 62894

You're getting ahead of yourself.

try:

$template->$field_name;

Why does this work?

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

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

Upvotes: 3

Related Questions