Return Values February 2nd, 2009
In #phpc we recently had a discussion about function return values; specifically from database queries.
I’m going to go on a (admittedly, rather sturdy looking) limb and say this applies to pretty much any function that returns from a data resource, not just a database .
My preference, is to return false only for error conditions, or when a function is supposed to only return one result (i.e. when selecting on a primary key) and fails to find any result.
However, it’s very rare that I care about whether I hit an error condition or just got no result when it comes to display — more to the point, my user doesn’t care.
There is a simply solution though, an empty array, also evaluates as false.
[php]
function getData()
{
if (error()) {
return false;
} elseif (noData()) {
return array();
} else {
return myData();
}
}
if (!$data = getData()) {
foreach ($data as $row) {
// Show data
}
} else {
echo “No data found.”;
}
// or
$data = getData();
if ($data === false) {
myLog(“Something Bad Happened!”);
}
if (!$data) {
echo “No data found.”;
} else {
// iterate
}
[/php]
This gives the best of both worlds IMO — the ability to distinguish error conditions or not depending on if you need to in the given context.
- Davey
P.S.
This might be the start of a series of thoughts on common API best practices
Finally added post-dates to my blog. If you're seeing them really huge, clear your cache :)
@dshafik [8 minutes ago]
New Blog Post: My contribution to Mentoring in the PHP Community: http://t.co/dMlKktq27T
@dshafik [29 minutes ago]
@jina totally jelly!
@dshafik [45 minutes ago]
“@Harris_Bryan: Georgia Tech is offering a 100% online masters for $6,000!! http://t.co/IUdZgmCOad” - the closing is food for thought...
@dshafik [10 hours ago]
@ChiperSoft aaaah, ours is 8-7:30 or later. That came at about 10 months too. Also wife gets up early, I sleep in. Except sunday. :D
@dshafik [22 hours ago]
















