Dutch PHP Conference 2023 - Call for Papers

ReflectionProperty::setValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::setValueDéfinit la valeur de la propriété

Description

public ReflectionProperty::setValue(object $object, mixed $value): void
public ReflectionProperty::setValue(mixed $value): void

Définit (modifie) la valeur de la propriété.

Liste de paramètres

object

L'objet à utiliser dans le cas d'une propriété non statique. Si la propriété est statique, nul besoin de préciser un objet, seul value est nécessaire.

value

La nouvelle valeur.

Valeurs de retour

Aucune valeur n'est retournée.

Historique

Version Description
8.1.0 Les propriétés privées et protégées sont immédiatement accessibles par ReflectionProperty::setValue(). Auparavant, elles devaient être rendues accessibles en appelant ReflectionProperty::setAccessible(), sinon une ReflectionException était déclenchée.

Exemples

Exemple #1 Exemple avec ReflectionProperty::setValue()

<?php
class Foo {
public static
$staticProperty;

public
$property;
protected
$privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

$reflectionClass->getProperty('staticProperty')->setValue('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); // Seulement nécessaire avant PHP 8.1.0.
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

L'exemple ci-dessus va afficher :

string(3) "foo"
string(3) "bar"
string(6) "foobar"

Voir aussi

add a note

User Contributed Notes 3 notes

up
1
me at ircmaxell dot om
11 years ago
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"
?>
up
1
p stewart imperial ac uk
5 months ago
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.
up
0
temirkhan.nasukhov
7 months ago
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::$age
To Top