首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

ReflectionProperty::setValue

(PHP 5, PHP 7)

ReflectionProperty :: setValue - 设置属性值

描述

代码语言:javascript
复制
public void ReflectionProperty::setValue ( object $object , mixed $value )
代码语言:javascript
复制
public void ReflectionProperty::setValue ( mixed $value )

设置(更改)该属性的值。

参数

object

如果该属性是非静态的,则必须提供一个对象来更改属性。如果属性是静态的,则该参数被省略并且只有value值需要被提供。

value

新的价值。

返回值

没有值返回。

错误/异常

如果属性不可访问,则抛出ReflectionException。您可以使用ReflectionProperty :: setAccessible()来访问保护或私有属性。

例子

示例#1 ReflectionProperty :: setValue()示例

代码语言:javascript
复制
<?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);
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

上面的例子将输出:

代码语言:javascript
复制
string(3) "foo"
string(3) "bar"
string(6) "foobar"

← ReflectionProperty::setAccessible

ReflectionProperty::__toString →

扫码关注腾讯云开发者

领取腾讯云代金券