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
How can I solve it? Looking for your valuable solutions.
Aucun commentaire:
Enregistrer un commentaire