Best practice for returning "error" from a function

You need exceptions:

public function CustomerRating() {
     $result = $db->query("...");
     $row = $result->fetch_assoc();
     if ($row !== null) {
          return $row['somefield'];
     } else {
          throw new Exception('There is an error with this rating.');
     }
}

// Somewhere on another page...
try {
    echo $class->CustomerRating();
} catch (Exception $e) {
    echo $e->getMessage();
}

There are (in my opinion) 2 common ways:

  1. Returning false
    Many builtin PHP functions do that

  2. Using SPL exceptions
    Evolved PHP frameworks (Symfony2, ZF2, ...) do that

Tags:

Php

Function