-
-
Notifications
You must be signed in to change notification settings - Fork 205
Description
In order to implement custom PHP serialization that's compatible with PHP versions 5.6 through 8.1 you need to implement both the __serialize() and __unserialize() methods and also implement the Serializable interface.
The reason for this is that __serialize() and __unserialize() are only supported in PHP >= 7.4, so Serializable needs to be used for earlier versions. However __serialize() and __unserialize() must also be implementated since PHP 8.1 otherwise a deprecated notice will be triggered.
Refs:
- https://www.php.net/manual/en/language.oop5.magic.php#object.serialize
- https://www.php.net/manual/en/class.serializable.php
PHPCompatibility rightly triggers a warning if the __serialize() and __unserialize() magic methods are implemented for code that runs on PHP < 7.4, but it doesn't consider whether the class also implements Serializable, in which case the warning should not be shown.
Here's an incorrectly failing test from WordPress core: https://github.com/WordPress/wordpress-develop/runs/4790971420?check_suite_focus=true
Here's some example code to reproduce the problem:
/**
* Controls how the object is represented during PHP serialization.
*
* @return string The PHP serialized representation of the object.
*/
public function serialize() {
return serialize( $this->__serialize() );
}
/**
* Controls how the object is represented during PHP serialization.
*
* Used by PHP >= 7.4.
*
* @return array The properties of the object as an associative array.
*/
public function __serialize() {
return get_object_vars( $this );
}
/**
* Controls how the object is reconstructed from a PHP serialized representation.
*
* @param string $data The PHP serialized representation of the object.
* @return void
*/
public function unserialize( $data ) {
$this->__unserialize( unserialize( $data ) );
}
/**
* Controls how the object is reconstructed from a PHP serialized representation.
*
* Used by PHP >= 7.4.
*
* @param array $data The associative array representation of the object.
* @return void
*/
public function __unserialize( $data ) {
foreach ( $data as $key => $value ) {
$this->$key = $value;
}
}