Skip to content
Advertisement

Using reflection class in PHP also unable to access private property

How to access private property values outside the class? I also tried using reflection in PHP.

JavaScript

Error: ` $ php src/Receipt.php PHP Fatal error: Uncaught Error: Cannot access private property TDDReceipt::$pending_amount in C:xampphtdocsall_scriptsPHPUnit_By_siddhusrcReceipt.php:48 Stack trace: #0 {main} thrown in C:xampphtdocsall_scriptsPHPUnit_By_siddhusrcReceipt.php on line 48

Fatal error: Uncaught Error: Cannot access private property TDDReceipt::$pending_amount in C:xampphtdocsall_scriptsPHPUnit_By_siddhusrcReceipt.php:48 Stack trace: #0 {main} thrown in C:xampphtdocsall_scriptsPHPUnit_By_siddhusrcReceipt.php on line 48 ` error screenshot

How can I solve it? Looking for your valuable solutions.

Advertisement

Answer

From the PHP manual for ReflectionProperty::setAccessible:

Enables access to a protected or private property via the ReflectionProperty::getValue() and ReflectionProperty::setValue() methods.

Calling setAccessible has no effect on access to the property via normal PHP syntax, only via that ReflectionProperty object.

So this line is still accessing a private property:

JavaScript

You need to instead access it via your reflection object:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement