24

How can I let the $foo variable below know that foo should be false?

class foo extends fooBase{

  private
    $stuff;

  function __construct($something = false){
    if(is_int($something)) $this->stuff = &getStuff($something);
    else $this->stuff = $GLOBALS['something'];

    if(!$this->stuff) return false;
  }

}

$foo = new foo(435);  // 435 does not exist
if(!$foo) die(); // <-- doesn't work :(

3 Answers 3

36

You cannot return a value from the constructor. You can use exceptions for that.

function __construct($something = false){
    if(is_int($something)) $this->stuff = &getStuff($something);
    else $this->stuff = $GLOBALS['something'];

    if (!$this->stuff) {
        throw new Exception('Foo Not Found');
    }
}

And in your instantiation code:

try {
    $foo = new foo(435);
} catch (Exception $e) {
    // handle exception
}

You can also extend exceptions.

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

4 Comments

you mean php.net/manual/en/language.exceptions.php ? but won't that show a php error and stop the script? I only want to return false ...
Not if you catch it. You can do anything you want from that point.
Then you are doing it wrong. Instead you should assign what ever variable is given and then call if ( $foo->is_falid() ){ /* do stuff */} , and please stop abusing die() function.
weird, you need the {} brackets in try catch even if you're writing a single statement :s
5

Constructor is not supposed to return anything.

If you need to validate data before using the to create an object, you should use a factory class.

Edit: yeah , exceptions would do the trick too, but you should not have any logic inside the constructor. It becomes a pain for unit-testing.

2 Comments

what's a factory class and how do I use it? :D
@Alex , watch this video , this might explain some of it ( yes , the example are in java , but it's a talk about theory and not "how to write hello world" ).
1

You can try

<?php

function __construct($something = false){ 
    $this->stuff = $something; 
}

static function init($something = false){
    $stuff = is_int($something) ? &getStuff($something) : $GLOBALS['something'];
    return $stuff ? new self($stuff) : false;
}


$foo = foo::init(435);  // 435 does not exist
if(!$foo) die();

Comments

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.