Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - constructor function doesn't return false

Tags:

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 :( 
like image 317
Alex Avatar asked May 06 '11 23:05

Alex


People also ask

Can a constructor return false?

No. Constructors do not have return values.

Can we return from constructor PHP?

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.

What are the __ construct () and __ destruct () methods in a PHP class?

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.

Can I call function in constructor PHP?

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.


2 Answers

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.

like image 123
webbiedave Avatar answered Sep 22 '22 12:09

webbiedave


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.

like image 28
tereško Avatar answered Sep 18 '22 12:09

tereško