Forum PHP 2025

ReflectionProperty::setRawValue

(PHP 8 >= 8.4.0)

ReflectionProperty::setRawValueset フックが定義されていたとしても、それを迂回してプロパティの値を設定する

説明

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

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
add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top