This is probably considered a really silly question, but I\'m in the process of putting together a simple template system for a website and am trying to keep track of my var
In my opinion the cleanest way to set it up is in array like this:
$tpl = array (
'title' => 'my title',
'desc' => 'my text'
);
You can combine it with Zane's answer also.
All the best!
arrays and objects are useful in case if you want to reset bulk of variable data after use it.
you can simply unset the array or destroy the object instead of unset range of variables use in a code.
Other than this arrays and objects have more symmetry in code and explanatory than normal variables
$tpl = array (
'title' => 'my title',
'desc' => 'my text'
);
Like Goran said, with the bonus that you could store these arrays in an ini file later and extract them as needed with parse_ini_file
Could be important if you want to permit users to write to their own ini file.
I would consider it unnecessary overhead. Doing what you are talking about in an object oriented way only means that inside your class you will have done nothing more than create a bunch of variables... just as you specified in your first example.
The array is the best way to go in my opinion. You are only using one variable... and you can also integrate it into your Class. So instead of $tpl->title, you may have $tpl->text['title']
In the end they are the same, It depends on the preference, although I would use arrays or objects because you can group variables in there, so you have things better sorted out.
Despite the objects method works I think it's not the natural intended use for it.
So I would say arrays!
Also, there are tons of php native functions you can use with arrays, like array_map()
or array_filter()
array sortings and etc etc...
In ideal scenarios every variable should belong to an object, other than the variables local to methods for temp purposes. However we don't live in an ideal world and specially our programming languages are far from it. Based on what the situation is, choose the best way to go about it to make your life easier. If you are using things for templates, generally you keep all the data in an array and extract
the array to get stand alone variables.
So yeah, the object method is the nicest, try to make it happen as much as you can without spending crazy amounts of time in doing it.
Also if you love objects and want to have the neat ->
way of doing it, you can do
$object = (object)$array;
That would convert your array to an object.
Hope that helps.