samedi 4 janvier 2020

How do I use reflection to get a class's properties in PHP?

I'm trying to use reflection to get details about an arbitrary object, but I'm getting conflicting and confusing feedback.

$dom = new DOMDocument;
$data = '<b>test</b>';
print '$dom: '; print_r($dom);
print 'get_object_vars(): '; print_r(get_object_vars($dom));
$r = new ReflectionObject($dom);
print '$r->getProperties(): '; print_r($r->getProperties());
print '$r->getStaticProperties(): '; print_r($r->getStaticProperties());
print '$r->hasProperty("textContent"): '; var_dump($r->hasProperty("textContent"));
print '$r->getProperty("textContent"): '; var_dump($r->getProperty("textContent"));

Here's what I get on PHP 7.4 when I run the above:

$dom: DOMDocument Object
(
    [doctype] => (object value omitted)
    [implementation] => (object value omitted)
    [documentElement] => (object value omitted)
    [actualEncoding] => 
    [encoding] => 
    [xmlEncoding] => 
<30 lines snipped>
)
get_object_vars(): Array
(
)
$r->getProperties(): Array
(
)
$r->getStaticProperties(): Array
(
)
$r->hasProperty("doctype"): bool(true)
$r->getProperty("doctype"): PHP Fatal error:  Uncaught ReflectionException: Property doctype does not exist ...

So basically,

  • print_r() (and var_dump()) dump useful information just fine

  • get_object_vars gives me an empty result

  • ReflectionObject->getProperties gives me an empty result

  • ReflectionObject->hasProperty() tells me that a property print_r() found does, indeed, exist...

  • ...aaaaand ReflectionObject->getProperty() to get the same property throws a ReflectionException. I'd like to invoke ReflectionProperty->setAccessible(true) in case it helps, but PHP is throwing in the process of getting a ReflectionProperty I could call that method on in the first place.

An understanding of what I am doing wrong would be greatly appreciated. Thanks!





Aucun commentaire:

Enregistrer un commentaire