note 54284 added to language.oop.constructor
| From: | mark at dreamjunky dot com | Date: | Wed, 29 Jun 2005 16:57:47 +0000 |
| Subject: | note 54284 added to language.oop.constructor | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-91140@lists.php.net to get a copy of this message | ||
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
}
}
----
Manual Page -- http://www.php.net/manual/en/language.oop.constructor.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54284
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54284&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54284&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54284&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54284&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54284&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54284&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54284&report=yes
Search -- http://master.php.net/manage/user-notes.php