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



Question:

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!


Solution:1

$template->{$field_name}  


Solution:2

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!";  }  


Solution:3

use

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

or simply

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »