Re: RFC: Deprecate json_encode() on classes marked as non-serializable
| From: | Rob Landers | Date: | Thu, 05 Sep 2024 09:47:57 +0000 |
| Subject: | Re: RFC: Deprecate json_encode() on classes marked as non-serializable | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-125435@lists.php.net to get a copy of this message | ||
On Thu, Sep 5, 2024, at 10:55, Alexandru Pătrănescu wrote:
>
> On Tue, Sep 3, 2024 at 2:27 PM Philip Hofstetter <phofstetter@sensational.ch> wrote:
>> Hello,
>>
>> As per my previous email to the list, I have now created the official RFC to deprecate
>> calling json_serialize() on instances of classes marked with ZEND_ACC_NOT_SERIALIZABLE.
>>
>> https://wiki.php.net/rfc/deprecate-json_encode-nonserializableÍ"3Ó?¼H
>> ô8hp1°
>>
>>
>
> Sharing my experience, I never use json_encode on objects but on arrays (that are both JSON
> objects or JSON arrays).
> When I see an object implementing JsonSerializable, I think it is the wrong approach, and I am
> usually able to find a better way.
> Maybe if we could go back in time, we would not allow json_encode on an object, except if it
> implemented JsonSerializable, but that ship sailed long ago.
>
> To your proposal, I think the BC break would be pretty big and I don't see a way it would
> pass.
> On https://www.php.net/json_encode we can read:
> > If a value to be serialized is an object, then by default only publicly visible properties
> > will be included.
> So that's the expected behaviour.
>
> Yes, you can say that encoding as JSON is just "another serialization method", but
> the default method in PHP, using json_encode()/json_decode(), is not symmetrical when using objects.
> And here lies the difference with serialize()/unserialize(), as this one aims to be
> symmetrical, and where it can't be, it has a way to stop the serialization.
>
> I am happy with the current way it works, getting an empty JSON object if there are no public
> properties for a Generator or Closure.
> And I don't think having an error for them would improve the language in a meaningful way,
> and the BC break is not worth it.
>
> Regards,
> Alex
>
To add to this, we apparently use json_encode at work to serialize custom exceptions, which appears
to work. This RFC would break that, I think.
— Rob