note 91104 deleted from language.oop5.magic by cmb
| From: | cmb@php.net | Date: | Sun, 10 Nov 2019 12:34:03 +0000 |
| Subject: | note 91104 deleted from language.oop5.magic by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212975@lists.php.net to get a copy of this message | ||
Note Submitter: zach at bygeekz dot com
----
Try this one on.
<?php
$ret = new Test(true);
var_dump((bool)(string)$ret);
var_dump($ret);
$ret=null;
$ret = new Test();
var_dump((bool)(string)$ret);
var_dump($ret);
class Test {
protected $state=null;
function __construct($state=null) {
$this->state = $state;
}
function __toString() {
if ($this->state) { return "1"; } else { return "0"; }
}
}
?>
You could for instance do..
if(!(bool)(string)$ret) { do_something!; }
Alternatively, just make state public, and check it.
if(!$ret->state) {}.
There is no automatic way I have found aside from some internal state check to verify a class. It
will always return an object. The only way around that is to force it out to string either where I
did, or $ret = (string) new Test(); then test the bool of your output..
if (!$ret) { echo "noooo!"; }
But now you have no calling methods, so I hope you passed some data in to get a usable string out.
Of course, if your class isn't named test, you can add a method..
public function test() {
return $this->state;
}
Logically that will work regardless of the _toString(), but I had hoped to post this to help others
see that there are a multitude of ways to check the validity of a class once it is loaded. In
__construct you can add any number of checks and set your state appropriately.