设置静态属性并调用非静态方法

时间:2014-08-04 13:35:42

标签: php reflection properties

我上课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()时,仍有旧值。如何告诉班级"使用"我在反思中设定的价值观?非常感谢!

1 个答案:

答案 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