Cleaning up your PHP code with printf
Nov 18, 2012
I build a lot of WordPress sites, and I often work on code from other developers. I have seen a fair bit of PHP code and it always bothers me when I see code like this:
<?php while($query->haveposts()): $query->thepost(); ?>
- "> <?php gettheimage(array('size' => 'slideshow', 'linktopost' => FALSE)); ?> <?php endwhile; ?>
The reason I cringe when I see that is
- It is tough to quickly understand what is happening
- I know mantainence time for that style of coding is higher.
How I usually deal with code like that is to move the code into a
sprintf() function. I am a fan of moving all variable assignments above the HTML code and then plugging the variables into the
printf() function, like so.
<?php while($query->haveposts()): $query->thepost();
$color = getfield('slidebackgroundcolor') ? thefield('slidebackgroundcolor') : '#000';
$image = gettheimage(array('size' => 'slideshow', 'linktopost' => false));
$href = get_permalink();
printf(' <li style="background:%s"> <a href="%s">%s</a> </li> ' , $color , $href , $image ); endwhile; ?> </ul>
There are a couple reasons why I like that:
- Since all the variables are defined before they are stuffed into the template, it is easier to debug if something is going crazy.
- It is easier to edit the HTML template. Define a new variable, add a place holder and plug the variable into the
- I can read and understand the code, quickly.
- The code is easier to maintain later on.
This is just my personal preference at the moment. I am sure there is a better way to do things, so if you have an opinion then toot your horn and let me know.↫ All Notes