首页 > 解决方案 > 如何在使用某个键访问 ArrayObject 之前执行/触发方法

问题描述

我有一个 php ArrayObject

class myObject extends ArrayObject
{
   
    public function __construct()
        parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
       // populate 
       $this->populateArray();
    {

    private function populateArray() {
       $this['hello'] = null;
       $this['hello2'] = null;
       $this['hello3'] = null;
    }
}

现在当我以这种方式访问​​ hello 元素时

 $myArray = new myObject();
 $value = $myArray['hello'];

我想触发 myObject 中的一个方法,该方法在读取之前将另一个对象分配给 $myArray。我的方法应该是这样的。

 private function method($value) {
    $this[$value] = new class2();
 }

有没有办法做到这一点?

标签: phpphp-7

解决方案


您可以像这样覆盖offsetGet函数:

    public function offsetGet($index) {
        $this->someMethod();
        return parent::offsetGet($index);
    }
    
    private function someMethod()
    {
        echo "triggered";
    }

然后当你跑

$x = new myObject;
echo $x['hello'];

将输出

触发

someMethod()你可以做任何你想做的事。


推荐阅读