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

Is there any option in PHP for "returning false" from a function and sending a corresponding message with this (as in what went wrong)?

Is an exception a better way to achieve this?

+4
source share
4 answers

throwing an exception is always good, but it is not literally equal return false
but if logic can withstand the exception, then it can be thrown away. May be of a specific type, not a general Exception though

+3
source

Yes, use exceptions; if you catch an exception, you can set the variable to false and also 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(); } 

That way, you can do whatever you want when something goes wrong.

+1
source

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

those. edit:

 function foo() { return true; } 

to

 function foo(&$ret) { if ( $something_went_wrong) return false; $ret = true; return true; } 
0
source
 function bla(){ return false; } if(bla() === false){ echo "Failed"; } 

But I think exceptions are better.

0
source

Source: https://habr.com/ru/post/1379968/


All Articles