PHP Conference Japan 2024

ReflectionProperty::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::__construct建構 ReflectionProperty 物件

說明

public ReflectionProperty::__construct(物件|字串 $class, 字串 $property)

參數

class

包含要反射的類別名稱的字串,或是一個物件。

property

要反射的屬性名稱。

錯誤/例外

嘗試取得或設定私有或受保護類別屬性的值將會導致拋出例外。

範例

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

<?php

class Str
{
public
$length = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('Str', 'length');

// Print out basic information
printf(
"===> The%s%s%s%s property '%s' (which was %s)\n" .
" having the modifiers %s\n",
$prop->isPublic() ? ' public' : '',
$prop->isPrivate() ? ' private' : '',
$prop->isProtected() ? ' protected' : '',
$prop->isStatic() ? ' static' : '',
$prop->getName(),
$prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
var_export(Reflection::getModifierNames($prop->getModifiers()), true)
);

// Create an instance of Str
$obj= new Str();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);

?>

上述範例將會輸出類似以下的結果

===> The public property 'length' (which was declared at compile-time)
     having the modifiers array (
  0 => 'public',
)
---> Value is: int(5)
---> Setting value to 10, new value is: int(10)
object(Str)#2 (1) {
  ["length"]=>
  int(10)
}

範例 #2 使用 ReflectionProperty 類別從私有和受保護屬性取得值

<?php

class Foo
{
public
$x = 1;
protected
$y = 2;
private
$z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true);
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true);
var_dump($prop->getValue($obj)); // int(2)

?>

上述範例將會輸出類似以下的結果

int(2)
int(3)

參見

新增註解

使用者貢獻的註解 1 則註解

geoffsmiths at hotmail dot com
7 年前
在範例 #2 中:註解 // int(2) 被標示,而私有屬性的值實際上是 3。(private $z = 3;)

var_dump($prop->getValue($obj)); // 這應該是 int(3)
To Top