note 37889 deleted from language.oop.constructor by danbrown

From: Date: Sat, 07 Nov 2009 18:57:39 +0000
Subject: note 37889 deleted from language.oop.constructor by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162532@lists.php.net to get a copy of this message
Note Submitter: steffen-staehle at NO dot SPAM dot gmx dot de ---- [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).

« previous php.notes (#162532) next »