PHP: Hypertext Preprocessor (original) (raw)

ReflectionClass::getProperty

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getProperty — Gets a ReflectionProperty for a class's property

Description

Parameters

name

The property name.

Examples

Example #1 Basic usage of ReflectionClass::getProperty()

<?php $class = new ReflectionClass('ReflectionClass'); <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>p</mi><mi>r</mi><mi>o</mi><mi>p</mi><mi>e</mi><mi>r</mi><mi>t</mi><mi>y</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">property = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8095em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">p</span><span class="mord mathnormal">ro</span><span class="mord mathnormal">p</span><span class="mord mathnormal" style="margin-right:0.02778em;">er</span><span class="mord mathnormal">t</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>class->getProperty('name'); var_dump($property); ?>

The above example will output:

object(ReflectionProperty)#2 (2) { ["name"]=> string(4) "name" ["class"]=> string(15) "ReflectionClass" }

Found A Problem?

eric at naeseth dot com

13 years ago

If the class doesn't have a property with the given name, a ReflectionException will be raised.

dohpaz42

9 years ago

`Accessing private properties is possible, but care must be taken if that private property was defined lower into the inheritance chain. For example, if class A extends class B, and class B defines a private property called 'foo', getProperty will throw a ReflectionException.

Instead, you can loop over getParentClass until it returns false to look for the private property, at which point you can access and/or modify its value as needed.

`