Re: __isset() and null value
| From: | Michael Voříšek - ČVUT FEL | Date: | Fri, 04 Sep 2020 18:07:57 +0000 |
| Subject: | Re: __isset() and null value | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111845@lists.php.net to get a copy of this message | ||
Your examples provide code for checking the existance of real
properties. But how to check existance of a magic one?
The best is currently __isset(), but to comply with isset() definition,
it should not return true when the magic property has null value, thus I
belive, there is currently not way (provided by php language) to check
for existance of magic property.
With kind regards / Mit freundlichen Grüßen / S přátelským pozdravem,
Michael Voříšek
On 4 Sep 2020 19:23, Marco Pivetta wrote:
Heya, On Fri, Sep 4, 2020 at 7:03 PM Michael Voříšek - ČVUT FEL <vorismi3@fel.cvut.cz> wrote:isset() returns false for null __isset() should return the same, but then if magic property with null value exists, there is no way to detect it Example: https://3v4l.org/GqUsh this is currently an limitation of php Ideally, we should introduce __exist() which should return true even if value is null and for BC autoimplement __isset() based on it and __get, ie. function __isset($n) { return $this->__exist($n) && $this->__isset($n) !== null; }I'd endorse **NOT** checking for property existence on objects that don't have a clearly defined interface/type: that's something for a static analyzer, not (usually) for runtime code. If you still need to do that (anti-patterns such as stuffing things instdClassinstances), checking if a property is defined is trivial with reflection: ```php <?php class SomethingMagicAndTerriblyUgly { public $foo = null; private $bar = null; } var_dump((new ReflectionClass(SomethingMagicAndTerriblyUgly::class))->hasProperty('foo')); var_dump((new ReflectionClass(SomethingMagicAndTerriblyUgly::class))->hasProperty('bar')); var_dump((new ReflectionClass(SomethingMagicAndTerriblyUgly::class))->hasProperty('baz')); ``` https://3v4l.org/pVC4j Checking if a **public** property exists at runtime is done viaarray_key_exists(), not viaisset(): ```php <?php class SomethingMagicAndTerriblyUgly { public $foo = null; private $bar = null; } var_dump(array_key_exists('foo', (array) (new SomethingMagicAndTerriblyUgly))); var_dump(array_key_exists('bar', (array) (new SomethingMagicAndTerriblyUgly))); ``` https://3v4l.org/ZLSjq Marco Pivettahttp://twitter.com/Ocramiushttp://ocramius.github.com/