如何在使用特定键访问 ArrayObject 之前 Execute/Trigger 方法

How to Execute/Trigger a method before an ArrayObject is accessed with a certain Key

我有一个 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();
 }

有办法实现吗?

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

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

那么当你 运行

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

会输出

triggered

someMethod()你可以为所欲为。