PHP Conference Japan 2024

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.2,PHP 7,PHP 8)

ReflectionClass::getStaticPropertyValue取得靜態屬性值

描述

public ReflectionClass::getStaticPropertyValue(字串 $name, 混合型別 &$def_value = ?): 混合型別

取得此類別上靜態屬性的值。

參數

name

要傳回值的靜態屬性名稱。

def_value

如果類別未宣告具有給定 name 的靜態屬性,則傳回的預設值。如果屬性不存在且省略此參數,則會拋出 ReflectionException

回傳值

靜態屬性的值。

範例

範例 #1 ReflectionClass::getStaticPropertyValue() 的基本用法

<?php
class Apple {
public static
$color = 'Red';
}

$class = new ReflectionClass('Apple');
var_dump($class->getStaticPropertyValue('color'));
?>

上述範例會輸出

string(3) "Red"

參見

新增註解

使用者貢獻的註解 2 個註解

Antares
13 年前
看來此方法具有與 getStaticProperties 方法不同的安全性層級。

如果您建立兩個看起來像這樣的類別 A 和 B

<?php
class A{
protected static
$static_var='foo';

public function
getStatic(){
$class=new ReflectionClass($this);
return
$class->getStaticPropertyValue('static_var');
}

public function
getStatic2(){
$class=new ReflectionClass($this);
$staticProps=$class->getStaticProperties();
return
$staticProps['static_var'];
}

public function
__construct(){
echo
$this->getStatic2();
echo
$this->getStatic();
}
}

class
B extends A{
protected static
$static_var='foo2';

}
?>

則 getStatic() 呼叫會輸出例外,而 getStatic2() 會正確傳回 'foo2';
Mauro Gabriel Titimoli
14 年前
如果您想變更變數類別的靜態屬性...

PHP 5.2
<?php
$reflection
= new ReflectionClass($className);
$staticPropertyReference = & $reflection->getStaticPropertyValue($staticPropertyName);

$staticPropertyReference = 'new value';
?>

PHP 5.3
<?php
$className
::$$classProperty
?>
To Top