How to access private property values outside the class? I also tried using reflection in PHP.
<?php namespace TDD; class Receipt { public $user_id = 1; private $pending_amount = 45; public function total(array $items = []){ $items[] = $this->pending_amount; return array_sum($items); } public function tax($amount,$tax){ return $amount * $tax; } public function pending() { return $this->pending_amount = 45; } public function addTaxPending($tax){ return $this->pending_amount * $tax; } } $class = new ReflectionClass('TDDReceipt'); $myProtectedProperty = $class->getProperty('pending_amount'); $myProtectedProperty->setAccessible(true); $myInstance = new Receipt(); $myProtectedProperty->setValue($myInstance, 99); echo $myInstance->pending_amount; ?>
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:
echo $myInstance->pending_amount;
You need to instead access it via your reflection object:
echo $myProtectedProperty->getValue($myInstance);