[RFC] Allow Readonly Property Defaults#22588
Conversation
| // Unserialization still bypasses normal readonly assignment semantics. | ||
| var_dump(unserialize("O:11:\"TestDefault\":0:{}")); | ||
| var_dump(unserialize("O:11:\"TestDefault\":1:{s:4:\"prop\";i:2;}")); | ||
| var_dump(unserialize("O:11:\"TestDefault\":2:{s:4:\"prop\";i:2;s:4:\"prop\";i:3;}")); |
There was a problem hiding this comment.
It is legal for properties to appear twice in serialization payload?! This probably should be deprecated and killed.
There was a problem hiding this comment.
Same answer here, the test is also just copied from 12 lines above. Intention was to confirm that having a default value makes no difference. Do you want me to change something? How?
There was a problem hiding this comment.
This was an unrelated remark about serialization in general. Often one notices odd behavior about PHP while reviewing PRs.
No action needed from your side.
There was a problem hiding this comment.
Looking at this once more after reading the RFC (and providing feedback on-list): I think this test is broken and effectively testing an implementation detail that is not usually observable.
The duplicate property is actually written twice (and readonly ignored) when no __unserialize() hook exists, but when an __unserialize() hook exists, only the latter version for the same key will be seen by the hook.
And similarly for a readonly property with a default value (i.e. the new feature), without __unserialize() the default will be overwritten, but __unserialize() will not be able to set it, because it is beholden to the regular readonly rules.
When you add:
public function __unserialize(array $data): void
{
foreach ($data as $key => $val) {
$this->{$key} = $val;
}
}
then you'll get:
Error: Cannot modify readonly property TestDefault::$prop in
The engine has a non-optimal error here. Will be addressed in a separate PR. Ref: php#22588 (comment)
RFC: https://wiki.php.net/rfc/readonly_property_defaults
Discussion thread: https://news-web.php.net/php.internals/131760
Voting thread: tbd