Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return values and exceptions for PHP functions

Tags:

exception

php

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?

like image 452
SHC Avatar asked Jun 26 '10 00:06

SHC


People also ask

What type of value can PHP functions return?

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.

How is it possible to return a value from a function in PHP?

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.

What are the exception class functions PHP?

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.

How do you use PHP to handle exceptions?

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.


1 Answers

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).

like image 133
Artefacto Avatar answered Sep 27 '22 18:09

Artefacto