note 54284 deleted from language.oop.constructor by danbrown

From: Date: Sat, 07 Nov 2009 18:57:16 +0000
Subject: note 54284 deleted from language.oop.constructor by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162524@lists.php.net to get a copy of this message
Note Submitter: mark at dreamjunky dot com ---- Responding to zax AT email DOT cz and others on the topic of pass/fail tests in constructors. Later versions of PHP don't allow $this = null, so that's out. Using unset($this) is allowed but is not reliable. Consider the following: class a { function a($pass) { if (!$pass) unset($this); } } echo ($a = new a(true) ? "Passed" : "False") . "\n"; echo ($a = new a(false) ? "Passed" : "False") . "\n"; The output: False False However, if you add a member variable to the class and run the same script, the output becomes: Pass Pass Basically the object evaluates to false if there are no member variables, otherwise true. I'm guessing, but I believe calling unset($this) only unsets the reference to the object. A copy of it is still passed back to the calling code. To sum up, I would stick with the original recommended solution of having a property specifically to represent an object's status: initialized or failed. class A { var $success; function A() { if (/* some fail test */) $this->success = false; // rest of your construct } }

« previous php.notes (#162524) next »