Get your FREE 30 page Developing SOLID Applications guide!

Attention Developers: Functions Should Return Things!

Out Of Date Warning

Languages change. Perspectives are different. Ideas move on. This article was published on October 9, 2008 which is more than two years ago. It may be out of date. You should verify that technical information in this article is still current before relying upon it for your own purposes.

Hey 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.

Learning design patterns doesn't have to suck.

Design patterns open a whole new world of possibilities. So why are you avoiding them? This brand new book will help you finally understand these wonderful programming techiques!

Learn design patterns TODAY »

There are currently no comments.