大网数据广告活动
PHP 语言与运行手册

ReflectionProperty::setValue · Set property value

· 52CE 我爱测

ReflectionProperty::setValue — Set property value

ReflectionProperty::setValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::setValue — Set property value

说明

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

Sets (changes) the property's value.

注意:

To set static property values, use ReflectionProperty::setValue(null, $value).

参数

object

For static properties, pass in null. For non-static properties, pass in the object.

value

The new value.

返回值

没有返回值。

更新日志

版本 说明
8.3.0 Calling this method with a single argument is deprecated, instead use ReflectionProperty::setValue(null, $value) for static properties.
8.1.0 Private and protected properties can be accessed by ReflectionProperty::setValue() right away. Previously, they needed to be made accessible by calling ReflectionProperty::setAccessible(); otherwise a ReflectionException was thrown.

示例

示例 #1 ReflectionProperty::setValue() 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));
?>

以上示例会输出:

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

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。