Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

ReflectionProperty

Read a property declaration and its value on an object.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new ReflectionProperty($class, $property)

Read a property declaration and its value on an object. For a typed property without a default, check isInitialized before getValue; reading it early throws Error. In PHP 8.4 reflection can access private properties without an explicit setAccessible call. The initialization rule applies to an ordinary backed property. In PHP 8.4 a virtual get hook can return 42 and report isInitialized true without assignment.

class Box { private int $n; }
$b=new Box(); $r=new ReflectionProperty(Box::class,"n"); $before=$r->isInitialized($b);
try{$r->getValue($b);}catch(Error $e){$early=get_class($e);}
$r->setValue($b,7); echo json_encode([$before,$early,$r->getValue($b)]);
class Computed {public int $answer {get => 42;}} $virtual=new ReflectionProperty(Computed::class,"answer"); $v=new Computed(); echo PHP_EOL,json_encode([$virtual->isVirtual(),$virtual->isInitialized($v),$virtual->getValue($v)]);
[false,"Error",7]
[true,true,42]

Examples

<?php
class Box { private int $n; }
$b=new Box(); $r=new ReflectionProperty(Box::class,"n"); $before=$r->isInitialized($b);
try{$r->getValue($b);}catch(Error $e){$early=get_class($e);}
$r->setValue($b,7); echo json_encode([$before,$early,$r->getValue($b)]);
class Computed {public int $answer {get => 42;}} $virtual=new ReflectionProperty(Computed::class,"answer"); $v=new Computed(); echo PHP_EOL,json_encode([$virtual->isVirtual(),$virtual->isInitialized($v),$virtual->getValue($v)]);

Result

[false,"Error",7]
[true,true,42]

Sources