CakeFest 2024: The Official CakePHP Conference

ReflectionProperty::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::__constructReflectionProperty オブジェクトを作成する

説明

public ReflectionProperty::__construct(object|string $class, string $property)

パラメータ

class

リフレクションするクラス、またはオブジェクトの名前を含む文字列。

property

調べたいプロパティの名前。

エラー / 例外

private あるいは protected なプロパティの値を取得あるいは設定しようとすると、 例外がスローされます。

例1 ReflectionProperty::__construct() の例

<?php
class Str
{
public
$length = 5;
}

// ReflectionProperty クラスのインスタンスを作成します
$prop = new ReflectionProperty('Str', 'length');

// 基本情報を表示します
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()), 1)
);

// Str のインスタンスを作成します
$obj= new Str();

// 現在の値を取得します
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// 値を変更します
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// オブジェクトを出力します
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 クラスを用いた、private および protected プロパティの値の取得

<?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)

参考

add a note

User Contributed Notes 1 note

up
5
geoffsmiths at hotmail dot com
6 years ago
At example #2: the comment // int(2) is stated while the value for the private property is actually 3. (private $z = 3;)

var_dump($prop->getValue($obj)); // This should be int(3)
To Top