What do you return when a function fails?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

What do you return when a function fails?

Post by raghavan20 »

Let's say you have a function to retrieve member id of the user from the user name.
Suppose you do find the user name invalid and you are not able to return the member id, do you return FALSE, 0 or appropriate error messages.

I used to return FALSE so far, but when I tried to echo the returned FALSE, I don't get anything it returns empty string not FALSE.

example scenario

Code: Select all

echo call_me(3); //This echo call returns no value,,,the return value is EMPTY instead of FALSE
echo call_me(10);//This returns 1 instead of TRUE,,,is this desirable as well...

function call_me($number){
if ($number == 10) return TRUE;
else return FALSE
}
1. If return TRUE actually returns 1, when is it possible to use "call_me(10) === TRUE",,,this kind of statement?
2. Do you feel the behaviors desirable??? Advise me the best coding practices....Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

false is actually returned.. it just doesn't "echo" naturally...
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

Well the "false" it returns isn't a string variable, it's a boolean variable.

Anytime you see a function returning either true or false in the way you showed, it won't actually echo those two words, it'll just make it so that you can identify whether or not the process was successful (1 or true) or a failure (0 or false).

See: http://php.net/manual/en/language.types.boolean.php

And PHP naturally interchanges 1 and true and 0 and false in regards to this sort of thing.

See: http://php.net/manual/en/language.types ... ggling.php
Post Reply