function return true vs return nothing

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
meee
Forum Newbie
Posts: 18
Joined: Wed Feb 04, 2009 1:38 pm

function return true vs return nothing

Post by meee »

Is it a good practice that I put in functions that don't return anything return true statement or can be without? I have two example. Is it ok to leave it like that?

Code: Select all

function checkAdminLogin ()
{
    if ( empty($_SESSION['administrator']) || $_SESSION['administrator']!=ADMINISTRATOR_PASSWORD) { 
        header ("Location: /administration/login.php");
    }
}

function updateCounter ()
{
      global $db;
      $db->query("UPDATE users SET counter=counter+1"); 
}
User avatar
mecha_godzilla
Forum Contributor
Posts: 375
Joined: Wed Apr 14, 2010 4:45 pm
Location: UK

Re: function return true vs return nothing

Post by mecha_godzilla »

You would normally return a value back to the calling script to confirm that the function() completed successfully (or otherwise).

Just looking at your first example, when you use header() you would normally use exit() afterwards to stop the rest of the script executing so you don't need to return any kind of status back to the calling script.

Similarly - with your second example - what happens if your database isn't available for some reason? If your DB class handles this situation itself then you don't need to return any values. This kind of failure becomes critical if you're saving information to the database or sending an email and the operation can't be completed - in these situations it's important that the user knows the operation has failed.

HTH,

Mecha Godzilla
Post Reply