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 :(
No. Constructors do not have return values.
You can do whatever you want with the return value of a constructor, so it's not true that "Nothing can be done with the return value of a constructor (aside from using the Object it created)." The return value of a constructor is not the object "it" created.
Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.
A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With