Re: In php 8.0: unable to distinguish between instance variable being null and unset

[email protected] (Alexandru Pătrănescu)
Newsgroups php.general
Message-ID <CAAwdEzCbePCTmyRYBAjOJM7pXzcW+PjDsTg7okUKgTgdbFN5Sg@mail.gmail.com>
Hey Emiel,


On Fri, Sep 3, 2021 at 3:09 PM Emiel Mols <[email protected]> wrote:

> Hello,
>
> Our codebase depends on distinguishing whether an instance variable is
> unset, or simply null:
>

Can you please share more on how you use this information? Is it for lazy
loading something that might not be loadable in the end?


>
> class C { public int $v = 123; }
> $x = new C; unset($x->v);
> $y = new C; $u->v = null;
>
> In php <8.0 we made this work with @array_key_exists($x, 'v'), which
> stopped working. isset($x->x) doesn't work, as it will return true for
> 'null' as well. property_exists($x, 'v') will always return true as long as
> the variable is declared: php-src here
> <https://github.com/php/php-src/blob/a13730c5e465b3c349a7970d15a49e4e132d4e07/Zend/zend_builtin_functions.c#L943>
> .
>
> Apart from using debug_zval_dump (too expensive), any hints?
>

I think the simplest solution would be to cast the object to an array and
you will see that the unset property will not be a key in the array while
the null one will be.
Another way to go here would be to use the magic method __get() that would
be called on the unset property. But not sure how that fits with your use
case.
Also something like this could work: https://3v4l.org/7NL0Y, trying to read
the property and handling the Error thrown.
But it all depends on how you use this... Please share more to help you
correctly.


> This feels like quite the oversight honestly :).
>

This feels like quite a special use case that could be implemented
differently to start with. Please share more information so we can help
better.
I guess you have read the rfc that deprecated this in 7.4 and scheduled for
later removal:
https://wiki.php.net/rfc/deprecations_php_7_4#array_key_exists_with_objects


>
> Best,
>
> Emiel
>

Alex
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.