Sanket Sahu
Sanket Sahu

Reputation: 8558

How to "return false" and send a message with it?

Is there any option in PHP to "return false" from a function and send a corresponding message with that (as in what went wrong)?

Is throwing an exception the best way to achieve this?

Upvotes: 4

Views: 2502

Answers (4)

Dunhamzzz
Dunhamzzz

Reputation: 14798

Yeah, use exceptions, if you catch an exception you can set the var to false as well as receive an error message.

function foo($a = null) {
     if(!$a) {
         throw new Exception('$a must be defined');
     }
}

try {
    $var = foo();
} catch(Exception $e) {
    $var = false;
    echo $e->getMessage();
}

This way you can do whatever you like when something goes wrong.

Upvotes: 1

Mob
Mob

Reputation: 11098

function bla(){
   return false;
}
if(bla() === false){
    echo "Failed";
}

But I believe exceptions are better.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157828

throwing an exception is always good but it is not literally equal to return false
but if you logic can sustain an exception, it's okay to throw it. May be of some distinct type, not general Exception though

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258548

You can change your function to return true or false on success or failure and return your variable in a parameter passed by reference.

I.e. change:

function foo()
{
   return true;
}

to

function foo(&$ret)
{
   if ( $something_went_wrong)
      return false;
   $ret = true;
   return true;
}

Upvotes: 0

Related Questions