JV’s Power Tips for PHP (1) - Using Objects to Store Multiple Output Values
(Page 6 of 7 )
Another reason why this is useful is that it files your output variables into one (or a few) objects. It also means that in our function get_template() we can get rid of this:
<?php
// etc.
// Make sure that all global variables are available to this functions..
foreach ( $GLOBALS as $key => $val )
{
global ${$key};
}
// etc.
?> ...which, in truth, is a little costly and replace it with this:
<?php
// etc.
// We only need to make the object $output global to this function..
global $output;
// etc.
?> Going back to our table template. It would look like this:
<table>
<tr>
<td>
$output->dynamic_text
</td>
</tr>
</table> Of course, you don’t have to write your own template system if you don’t want to. I just happen to be a control freak who likes to know the structure of all the code I use. There are plenty of pre-built template systems out there that can save you hours of coding (e.g.
Smarty). Even so, the principle is still the same:
- Don’t break out of PHP tags.
- Abstract HTML content from programming logic.
Next: Conclusion >>
More PHP Articles
More By Justin Vincent