Failed to get dynamic instance variables via PHP reflection

I was not able to get dynamic instance variables via PHP reflection

Code example:

<?php

class Foo
{
    public function bar()
    {         
        $reflect = new ReflectionClass($this);
        $props   = $reflect->getProperties();
        var_export($props);
        die;
    }
}

$foo = new Foo();
$foo->a = "a";
$foo->b = "b";

$foo->bar(); // Failed to print out variable a and b

Any idea?

+4
source share
3 answers

ReflectionClass::getProperties()gets only properties explicitly defined by the class. To reflect all the properties set for an object, use ReflectionObjectone that inherits from ReflectionClassand works with run-time instances:

$reflect = new ReflectionObject($this);

Or, as Tim Cooper said , forget about thinking and just use it get_object_vars().

+8
source

You cannot use ReflectionClassin this situation. Replace the variable $propsas follows:

$props = get_object_vars($this);

, ReflectionObject (. BoltClock), .

+4

$object             = new class()
{
    private $fooPrivate = 'barPrivate';

    public $fooPublic = 'barPublic';

    public static $fooStaticPublic = 'barStaticPublic';

    public function getProperties(): array
    {
        return get_object_vars( $this );
    }
};

$object->fooDynamic = 'barDynamic';

ReflectionClass

/** lists: 'fooPrivate', 'fooPublic', 'fooStaticPublic' */
var_export(
    ( new ReflectionClass( $object ) )
        ->getProperties()
);

/** lists: 'fooPublic', 'fooStaticPublic' */
var_export(
    ( new ReflectionClass( $object ) )
        ->getProperties( ReflectionProperty::IS_PUBLIC )
);

ReflectionObject

/** lists: 'fooPrivate', 'fooPublic', 'fooStaticPublic', 'fooDynamic' */
var_export(
    ( new ReflectionObject( $object ) )
        ->getProperties()
);

/** lists: 'fooPublic', 'fooStaticPublic', 'fooDynamic' */
var_export(
    ( new ReflectionObject( $object ) )
        ->getProperties( ReflectionProperty::IS_PUBLIC )
);

get_object_vars()

/** lists: 'fooPublic', 'fooDynamic' */
var_export(
    get_object_vars( $object )
);

/** lists: 'fooPrivate', 'fooPublic', 'fooDynamic' */
var_export(
    $object->getProperties()
);

  • ReflectionClass::getProperties()
  • ReflectionObject::getProperties()
  • ReflectionClass::getProperties() ReflectionObject::getProperties()
  • get_object_vars()
    • , , ,
0

Source: https://habr.com/ru/post/1790312/


All Articles