Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

<?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('TDD\Receipt');
$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 TDD\Receipt::$pending_amount in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php:48
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php on line 48

Fatal error: Uncaught Error: Cannot access private property TDD\Receipt::$pending_amount in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php:48
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php on line 48
`
error screenshot

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading