note 37889 added to language.oop.constructor

From: Date: Mon, 01 Dec 2003 14:08:02 +0000
Subject: note 37889 added to language.oop.constructor
Groups: php.notes 
Request: Send a blank email to php-notes+get-61207@lists.php.net to get a copy of this message
[in reply to ogarbe's comment (01-Apr-2003)] Any object evaluation as boolean of the kind <? if ($a = new A()) { // success, use $a ... } ?> is dangerous. Whether an object evaluates as true or false seems to depend on its internal structure (I've tested on a rather oldish version of php (4.2.1), though, so this might have changed!). Even a successfully created object might evaluate as false. Compare the two classes: <? class TestBool1 { var $somevar = 'hello world'; function TestBool1() { echo "1 somevar is: $this->somevar<p>"; } // constructor } // TestBool if ($obj = new TestBool1()) echo 'obj is valid<p>'; else echo 'obj is invalid<p>'; class TestBool2 { function TestBool2($somevar) { echo "2 somevar is: $somevar<p>"; } // constructor } // TestBool if ($obj = new TestBool2('hello world')) echo 'obj is valid<p>'; else echo 'obj is invalid<p>'; ?> The output is: 1 somevar is: hello world obj is valid 2 somevar is: hello world obj is invalid Case '2' is NOT what you would expect. So at least you should use another comparison: <? class TestBool3 { function TestBool3($somevar) { echo "3 somevar is: $somevar<p>"; // assume error $this = NULL; } // constructor } // TestBool if (($obj = new TestBool3('hello world')) !== NULL) echo 'obj is valid<p>'; else echo 'obj is invalid<p>'; ?> This evaluates correctly and prints: 3 somevar is: hello world obj is invalid But Markus 16-Sep-2003 says assigning NULL to $this did not work any more with php 4.3.3. So what it boils down to: I still prefer the solution I have sketched below (steffen 17-Jan-2003). ---- Manual Page -- http://www.php.net/manual/en/language.oop.constructor.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37889 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37889&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37889&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#61207) next »