使用 ReflectionClass 获取运行时属性

Getting runtime properties with ReflectionClass

所以我正在探索反射的使用 class。我注意到几件事。 在能够使用 Origin class 中的 属性 Even 的值或名称之前,必须设置我的 属性 的可访问性。

我想知道是否可以通过 ReflectionClass 在运行时设置属性。例如

class MyClass
{
    public $bathroom = 'Dirty';
    protected $individual = 'President';
    private $conversation = '****************';

    function outputReflectedPublic()
    {
        $reflection = new ReflectionClass($this);
        $props = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
        foreach($props as $prop)
            echo $prop->getName() . ' : ' . $prop->getValue($this);
    }
}

$obj = new MyClass();
$obj->outputReflectedPublic();//bathroom : Dirty
//now we add a new property
$obj->$ect = 'ify';
$obj->outputReflectedPublic();//bathroom : Dirty  //same as before

现在我对此并不感到太惊讶了。 我试图查看 属性 是否在实例中作为 protected/Private/Static 与 ReflectionProperty::IS_PRIVATEReflectionProperty::IS_PROTECTEDReflectionProperty::IS_STATIC

我也用了$prop->setAccessible(true)来防止无法访问的错误。 我无法看到 $ect 属性.

我能够通过这样的内部函数获得 $ect 属性:

function getAll()
{
    foreach($this as $key=>$val)
        echo $key . ' : ' . $val . '<br>';
}

bathroom : Dirty

individual : President

converstation : ****************

ect : ify

有没有办法从 ReflectionClass 的对象中获取该($ect)类型的属性?这些属性的正式名称是什么?

ReflectionClass::getProperties() 仅获取 class 明确定义的属性。要反映您在对象上设置的所有属性,包括动态属性,请使用 ReflectionObject,它继承自 ReflectionClass 并适用于运行时实例:

$reflect = new ReflectionObject($this);