Heya,

<http://ocramius.github.com/>


On Fri, Sep 4, 2020 at 7:03 PM Michael Voříšek - ČVUT FEL <
voris...@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 in
`stdClass` instances), 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 via
`array_key_exists()`, not via `isset()`:

```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 Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/

Reply via email to