Skip to content

Commit

Permalink
Code Modernization: Fix "JsonSerializable_Object::jsonSerialize() s…
Browse files Browse the repository at this point in the history
…hould be compatible with `JsonSerializable::jsonSerialize(): mixed`" error on PHP 8.1.

This relates to the [https://wiki.php.net/rfc/internal_method_return_types Return types for internal methods RFC] in PHP 8.1 and in particular, the change made in [php/php-src#7051 PHP PR #7051], which adds a `mixed` return type to the `JsonSerializable::jsonSerialize()` interface method.

WordPress only contains one (test) class which implements the `JsonSerializable` interface and this commit fixes the issue for that class.

As of PHP 8.1, the `jsonSerialize()` method in classes which implement the `JsonSerializable` interface are expected to have a return type declared. The return type should be `mixed` or a more specific type. This complies with the Liskov principle of covariance, which allows the return type of a child overloaded method to be more specific than that of the parent.

The problem with this is that:
1. The `mixed` return type was only introduced in PHP 8.0.
2. Return types in general were only introduced in PHP 7.0.

WordPress still has a minimum PHP version of 5.6, so adding the return type is not feasible for the time being.

The solution chosen for now is to add an attribute to silence the deprecation warning. While attributes are a PHP 8.0+ feature, due to the choice of the `#[]` syntax, in PHP < 8.0, attributes will just be ignored and treated as comments, so there is no drawback to using the attribute.

Props jrf.
See #53635.

git-svn-id: https://develop.svn.wordpress.org/trunk@51517 602fd350-edb4-49c9-b593-d223f7449a82
  • Loading branch information
SergeyBiryukov committed Jul 30, 2021
1 parent 108d4d1 commit 17fb931
Showing 1 changed file with 1 addition and 0 deletions.
1 change: 1 addition & 0 deletions tests/phpunit/includes/class-jsonserializable-object.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function __construct( $data ) {
$this->data = $data;
}

#[ReturnTypeWillChange]
public function jsonSerialize() {
return $this->data;
}
Expand Down

0 comments on commit 17fb931

Please sign in to comment.