PHP Conference Japan 2024

ReflectionProperty::getValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::getValue取得值

描述

public ReflectionProperty::getValue(?object $object = null): mixed

取得屬性的值。

參數

object

如果屬性是非靜態的,則必須提供一個物件來獲取屬性。如果您想在不提供物件的情況下獲取預設屬性,請改用 ReflectionClass::getDefaultProperties()

返回值

屬性的目前值。

更新日誌

版本 描述
8.1.0 現在可以直接透過 ReflectionProperty::getValue() 存取私有和受保護的屬性。先前,需要透過呼叫 ReflectionProperty::setAccessible() 使它們可存取;否則會拋出 ReflectionException
8.0.0 object 現在可以為 null。

範例

範例 #1 ReflectionProperty::getValue() 範例

<?php
class Foo {
public static
$staticProperty = 'foobar';

public
$property = 'barfoo';
protected
$privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true); // 僅在 PHP 8.1.0 之前需要
var_dump($reflectionProperty->getValue(new Foo));
?>

以上範例將輸出

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

參見

新增註釋

使用者提供的註釋 1 則註釋

sergiy dot sokolenko at gmail dot com
14 年前
要存取受保護和私有的屬性,您應該使用
ReflectionProperty::setAccessible(bool $accessible)

<?php
/** 含有 protected 和 private 成員的 Foo 類別 */
class Foo {
protected
$bar = 'barrr!';
private
$baz = 'bazzz!';
}

$reflFoo = new ReflectionClass('Foo');
$reflBar = $reflFoo->getProperty('bar');
$reflBaz = $reflFoo->getProperty('baz');

// 設定 private 和 protected 成員可供 getValue/setValue 存取
$reflBar->setAccessible(true);
$reflBaz->setAccessible(true);

$foo = new Foo();
echo
$reflBar->getValue($foo); // 將輸出 "barrr!"
echo $reflBaz->getValue($foo); // 將輸出 "bazzz!"

// 您也可以使用 setValue 設定值
$reflBar->setValue($foo, "new value");
echo
$reflBar->getValue($foo); // 將輸出 "new value"
?>
To Top