(PHP 8 >= 8.4.0)
ReflectionProperty::setRawValue — set フックが定義されていたとしても、それを迂回してプロパティの値を設定する
set
フックが定義されていたとしても、それを迂回してプロパティの値を設定します。
object
value
値を返しません。
プロパティが仮想プロパティの場合、 Error がスローされます。 なぜなら、設定する生の値がないからです。
例1 ReflectionProperty::setRawValue() の例
<?php
class Example
{
public int $age {
set {
if ($value <= 0) {
throw new \InvalidArgumentException();
}
$this->age = $value;
}
}
}
$example = new Example();
$rClass = new \ReflectionClass(Example::class);
$rProp = $rClass->getProperty('age');
// フックを経由して値を設定し、例外がスローされます
try {
$example->age = -2;
} catch (InvalidArgumentException) {
echo "InvalidArgumentException for setting property to -2\n";
}
try {
$rProp->setValue($example, -2);
} catch (InvalidArgumentException) {
echo "InvalidArgumentException for using ReflectionProperty::setValue() with -2\n";
}
// しかし、下記は $age に -2 を設定してもエラーが発生しません。
$rProp->setRawValue($example, -2);
echo $example->age;
?>
上の例の出力は以下となります。
InvalidArgumentException for setting property to -2 InvalidArgumentException for using ReflectionProperty::setValue() with -2 -2