-   Programming (
-   -   PHP5: Logical Operators vs. If-Else (

unreal128 11-15-2006 08:07 PM

PHP5: Logical Operators vs. If-Else
I am creating a class function that connects to a mySQL server and then selects a database. There are two approaches to creating a segment of this code.

1st approach

if ( !($this->connection =@ mysql_connect($sqlhost, $sqluser, $sqlpw)) ) {
    return false;
if ( mysql_select_db($sqldb, $this->connection) ) {
    return true;
} else {
    return false;

2nd approach

$this->connection =@ mysql_connect($sqlhost, $sqluser, $sqlpw) || return false;
mysql_select_db($sqldb, $this->connection) || return false;
return true;

Which is the better choice and why?

graemef 11-15-2006 10:50 PM

The first approach is the conventional approach, the second relying on the logical operators being implemented as short circuit logical operators. Because most people will find the first approach easier or even a more natural style I'd go with that. Also it allows more do be done, if for example you want to write to a log file where it failed before returning it is trivial to add that code.

unreal128 11-15-2006 10:52 PM

Thanks for the feedback. I guess I am just on a quest to trim down my code and still make it easy to read.

All times are GMT -5. The time now is 07:52 AM.