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...");
}
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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: ...');
}

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.