note 128024 added to reflectionproperty.setvalue
| From: | pstewartimperialacuk at main dot php dot net | Date: | Fri, 16 Dec 2022 15:18:43 +0000 |
| Subject: | note 128024 added to reflectionproperty.setvalue | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219980@lists.php.net to get a copy of this message | ||
setValue can be used for readonly properties, but only if the property has not yet been initialised:
<?php
class Person
{
private readonly int $age;
public function __construct(array $props = []) {
if (isset($props['age'])) {
$this->age = (int)$props['age'];
}
}
}
$personWithKnownAge = new Person(['age' => 50]);
$reflection = new ReflectionProperty($personWithKnownAge, 'age');
$reflection->setValue($personWithKnownAge, 10); // Fails - Age is already initialised, value
cannot be changed.
$personWithUnknownAge = new Person();
$reflection = new ReflectionProperty($personWithUnknownAge, 'age');
$reflection->setValue($personWithUnknownAge, 10); // Succeeeds - Age is not yet initialised,
value can be set.
?>
This can be useful for situations where it is desirable to initialise properties from outside of the
defining class, for example an ORM setup where the parent class is responsible for setting
properties on a model subclass instance.
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.175 (proxied: 81.187.221.162)
----
Manual Page -- https://php.net/manual/en/reflectionproperty.setvalue.php
Edit -- https://main.php.net/note/edit/128024
Del: integrated -- https://main.php.net/note/delete/128024/integrated
Del: useless -- https://main.php.net/note/delete/128024/useless
Del: bad code -- https://main.php.net/note/delete/128024/bad+code
Del: spam -- https://main.php.net/note/delete/128024/spam
Del: non-english -- https://main.php.net/note/delete/128024/non-english
Del: in docs -- https://main.php.net/note/delete/128024/in+docs
Del: other reasons-- https://main.php.net/note/delete/128024
Reject -- https://main.php.net/note/reject/128024
Search -- https://main.php.net/manage/user-notes.php