[英]Using reflection class in PHP also unable to access private property
如何访问 class 之外的私有属性值? 我还尝试在 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} 在第 48 行的 C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.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 第 48 行`错误截图
我该如何解决? 寻找您有价值的解决方案。
来自ReflectionProperty::setAccessible 的 PHP 手册:
通过 ReflectionProperty::getValue() 和 ReflectionProperty::setValue() 方法启用对受保护或私有属性的访问。
调用setAccessible
对通过普通 PHP 语法访问属性没有影响,只能通过 ReflectionProperty object 访问。
所以这一行仍在访问私有属性:
echo $myInstance->pending_amount;
您需要通过反射 object 来访问它:
echo $myProtectedProperty->getValue($myInstance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.