0

How can I check if my object has returned false or not? I have the following class:

class Test {
    public function __construct($number) {
        if($number != '1') {
            return FALSE;
        }
    }
}

I've tried:

$x = new Test('1');
$x = new Test('2');

But when I var_dump($x), I get the same results. I want to do a:

if(! $x = new Test('1')) {
    header("location: xxx...");
}
deceze
  • 510,633
  • 85
  • 743
  • 889
execv
  • 822
  • 1
  • 8
  • 23

2 Answers2

6

You cannot return anything from a constructor. If you want the construction of an object to fail, you'll have to throw an Exception.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

As deceze said, constructors cannot return a value. You could create a factory method that returns false, like:

class Test
{
    public function __construct($number) {
        ...
    }

    public function factory($number) {
        return ($number != '1') ? false : new self($number);
    }
}

$x = Test::factory('1');
if (!$x) {
    header('Location: ...');
}

But I would use exceptions instead

class Test
{
    public function __construct($number) {
        if ($number != '1') {
            throw new IllegalArgumentException('Number must be "1"');
        }
        ...
    }
}

try {
    $x = new Test('1');
} catch (Exception $e) {
    header('Location: ...');
}
rr.
  • 6,484
  • 9
  • 40
  • 48
  • Ok. Is it best for me to try & catch each time I create new object, or can I do it once in the class and have it handle it? (Which is better practice)? – execv Jan 11 '12 at 01:43
  • 2 additional questions: 1. Should I try/catch for every method? (ie: try { $user->getEmail(); } catch(..) { .. }. 2. Should I try/catch when validating form data? (ie: $data['name'] = ''; $user->updateName($data); // if the method finds that name is empty, should it just return a message, or should I throw an exception?) – execv Jan 11 '12 at 01:45
  • @Nathan You should not `catch` any and all exceptions simply because they may be thrown. Exceptions are, as the name says, *exceptional circumstances* which *should never happen*. If they do happen, it's because there's an error in your application, which is why you're declaring an *exceptional situation*. Don't use exceptions for normal "may or may not happen" circumstances, most exceptions should specifically *not* be caught, especially in a trivial case like this. – deceze Jan 11 '12 at 01:48