我有一个类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()
时,仍然有旧的值。如何告诉类"使用"我在反射中设置的值?非常感谢!
我自己解决。我所要做的就是从反射中创建新的实例:
$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