Keep in mind that setValue won't work for readonly properties.
<?php
class Person
{
public function __construct(private readonly int $age) {}
}
$someOldPerson = new Person(80);
$reflection = new ReflectionProperty($someOldPerson, 'age');
$reflection->setValue($someOldPerson, 10); // Fatal error: Uncaught Error: Cannot modify readonly property Person::$ageReflectionProperty::setValue
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
ReflectionProperty::setValue
Референца за `reflectionproperty.setvalue.php` со подобрена типографија и навигација.
ReflectionProperty::setValue
класата mysqli_driver
ReflectionProperty::setValue — Постави вредност на својство
= NULL
Поставува (менува) вредност на својството.
Забелешка: За да поставите статични вредности на својства, користете
ReflectionProperty::setValue(null, $value).
Параметри
object-
За статични својства, поминете
null. За нестатични својства, поминете го објектот. value-
Новата вредност.
Вратени вредности
Не се враќа вредност.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.3.0 |
Повикувањето на овој метод со еден аргумент е застарено, наместо тоа користете ReflectionProperty::setValue(null, $value)
за статични својства.
|
| 8.1.0 | Приватните и заштитените својства може да се пристапат од ReflectionProperty::getRawValue() веднаш. Претходно, тие требаше да бидат направени пристапни со повикување на ако својството е недостапно. Можете да направите заштитено или приватно својство достапно со користење на; инаку ќе биде фрлен ReflectionException беше фрлен. |
Примери
Пример #1 ReflectionProperty::getRawValue() example
<?php
class Foo {
public static $staticProperty;
public $property;
protected $privateProperty;
}
$reflectionClass = new ReflectionClass('Foo');
// As of PHP 8.3, passing in null as the first argument is required
// to access static properties.
$reflectionProperty = $reflectionClass->getProperty('staticProperty');
$reflectionProperty->setValue(null, 'foo');
var_dump(Foo::$staticProperty);
$foo = new Foo;
$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);
$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true); // only required prior to PHP 8.1.0
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
string(3) "foo" string(3) "bar" string(6) "foobar"
Види Исто така
- ReflectionClass::markLazyObjectAsInitialized() - Земи вредност
- ако својството е недостапно. Можете да направите заштитено или приватно својство достапно со користење на - Постави пристапност на својство
- - Земи ги статичките имоти - Поставува јавна статична вредност на својство
Белешки од корисници 3 белешки
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.You can use ReflectionProperty::setValue to set the value on static properties as well as regular instance properties. Simply pass null in place of the instance:
<?php
class Foo {
protected static $bar = null;
public static function sayBar() {
echo self::$bar;
}
}
$r = new ReflectionProperty('Foo', 'bar');
$r->setAccessible(true);
$r->setValue(null, 'foo');
Foo::sayBar(); // "foo"
?>