I’m having some problems getting my object to gracefully fail out if an invalid parameter is given during instantiation. I have a feeling it’s a small syntax thing somewhere that I simply need fresh eyes on. Any help is more than appreciated.
class bib { protected $bibid; public function __construct($new_bibid) { if(!$this->bibid = $this->validate_bibid($new_bibid)) { echo 'me'; return false; } //carry on with other stuff if valid bibid } private static function validate_bibid($test_bibid) { //call this method every time you get a bibid from the user if(!is_int($test_bibid)) { return false; } return (int)$test_bibid; } }
Note that I have an ‘echo me’ line in there to demonstrate that it is in fact, returning false. The way that I’m calling this in my PHP is as follows:
if(!$bib=new bib('612e436')) { echo 'Error Message'; } else { //do what I intend to do with the object }
This outputs the me from above, but then continues on into the else block, doing what I intend to do with a valid object.
Can anyone spot anything I’m doing wrong in there?
Thanks!
You can’t return in a constructor in PHP – the object is still created as normal.
You could use a factory or something similar;
Or throw an exception in the constructor and use a try catch instead of the if statement.