I'm reading some books on PHP (specifically "PHP and MySQL Web Development" by Welling and Thomson) and I'm also a fresh undergrad. I was a bit curious why the author decided to choose two different ways to terminate the execution of a function, e.g.
if (!$result) {
throw new Exception('Password could not be changed.');
} else {
return true;
}
For me, this seems a bit inconsistent and it would make more sense to return false and have the caller check the callee's return value and deal with it. Is it common for PHP code to be like this? Is this the type of style expected when using exceptions?
Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.
Definition and UsageThe return keyword ends a function and, optionally, uses the result of an expression as the return value of the function. If return is used outside of a function, it stops PHP code in the file from running.
An exception is an object that describes an error or unexpected behaviour of a PHP script. Exceptions are thrown by many PHP functions and classes. User defined functions and classes can also throw exceptions. Exceptions are a good way to stop a function when it comes across data that it cannot use.
The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.
Yes, I agree it doesn't make much sense. Either signal error conditions through the return value or with an exception. If the return value is always true
(on error an exception is raised), you might as well not return anything (which in PHP is equivalent to returning NULL
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With