我上课Filter
:
class Filter
{
private static $filters = array('foo', 'bar');
public function getFilters()
{
return self::$filters;
}
}
此类没有$filters
的setter,但我需要更改其值。在我看来,反思是实现这一目标的好方法,所以我尝试了:
$filter = new Filter(); // Create instance of my object
$reflection = new ReflectionObject($filter); // Create its reflection
$filters = $reflection->getProperty('filters'); // Get property reflection ...
$filters->setAccessible(true); // ... and set it to public
$filters->setValue(null, array()); // Set new value
现在,$filters
应为空,但当我致电$filter->getFilters()
时,仍有旧值。如何告诉班级"使用"我在反思中设定的价值观?非常感谢!
答案 0 :(得分:0)
好吧,我自己解决了。我所要做的就是从反射创建新实例:
$filter = new Filter();
$reflection = new ReflectionObject($filter);
$filters = $reflection->getProperty('filters');
$filters->setAccessible(true);
$filters->setValue(null, array());
$filter = $reflection->newInstance();
$filter->getFilters(); // It's correct now