Reputation: 8558
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
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
Reputation: 11098
function bla(){
return false;
}
if(bla() === false){
echo "Failed";
}
But I believe exceptions are better.
Upvotes: 0
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
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