Attention Developers: Functions Should Return Things!
October 9th, 2008 @ 7:25 pmHey you…yeah you PHP developer, stop doing this:
<?php
function foo($bar)
{
$baz = '<p class="myclass">' . $bar . ' is cool!</p>';
echo $baz;
}
?>That’s bad. Really bad. It’s frustrating. Particularly to a developer who comes after you, and wants to deal with the output themselves, for any number of reasons.
Please, when you write functions, return something, anything, kind of like this:
<?php
function foo($bar)
{
$baz = $bar . ' is cool!';
return $baz;
}
echo '<p class="myclass">'. foo('PHP') . '</p>';
?>Why is this useful? By returning the string instead of outputting it, you give another developer who might interface with your function the ability to muck with the string themselves. Having played with WordPress all day, I can say from experience that having the output thrust upon me by default is a bad way of doing things. Bad, bad developers.
So please, return things. It provides the most flexibility for everybody, and makes it easier to use the code.
The original work of Brandon Savage.
No related posts.
Categories: Best Practices, Web ArchitectureTags: , Best Practices, functions, readabilityThere are currently no comments.
Web developer, amateur photographer, traveller, and amatuer chef. Expect to find me writing code, visiting new places or trying a new recipe. I live with my wife in Olney, Maryland. Follow Me On Twitter!- New Rockville PHP Group
- Excited About PHP Again
- Rethinking The Technical Resume
- We The State, Not We The People
- Working To Defeat the Stop Online Piracy Act
- Diversifying This Blog
- What do you want the web to be?
- Why I Love Being An Engineer
- Validation Blind Spots Hurt Real Users
- Finding A Job Without A Recruiter


