2

通常使用java。我今天看到了这样的片段

$oStrategie = new Strategie();

foreach($aData as $key=>$value) {
        $oStrategie[$key] = $value;
}

$oStrategie->doSomething()

Strategie 是一个自制的 php 类,没有什么特别之处。简单的构造函数什么都不做,等等。

在 Strategie 类中,方法 doSomething() 访问 $aData 的 ArrayValues

$this['array_index_1'] 

为什么即使 Strategie 类没有定义任何属性并且没有覆盖 setter 或类似的东西,我也可以访问那里的数组?谁能解释一下那里发生了什么?php中的类中不需要有属性???

4

1 回答 1

3

你的类实现了ArrayAccess接口。这意味着它实现了以下方法:

ArrayAccess {
    abstract public boolean offsetExists ( mixed $offset )
    abstract public mixed offsetGet ( mixed $offset )
    abstract public void offsetSet ( mixed $offset , mixed $value )
    abstract public void offsetUnset ( mixed $offset )
}

这允许您对此类的实例使用数组访问$var[$offset]。这是一个像这样的类的标准实现,使用$container数组来保存属性:

class Strategie implements ArrayAccess {

    private $container = array();

    public function __construct() {
        $this->container = array(
            "something"   => 1,
        );
    }
    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

如果不查看它的实际实现Strategie或派生它的类,很难判断它实际在做什么。

但是使用它,您可以控制类的行为,例如,在访问不存在的偏移量时。假设我们替换offsetGet($offset)为:

public function offsetGet($offset) {
    if (isset($this->container[$offset])) {
        return $this->container[$offset];
    } else {
        Logger.log('Tried to access: ' + $offset);
        return $this->default;
    }
}

现在,每当我们尝试访问一个不存在的偏移量时,它将返回一个默认值(例如:)$this->default并记录一个错误,例如。

请注意,您可以使用魔术方法__set()__get()和来完成类似__isset()的行为__unset()。我刚刚列出的魔术方法之间的区别在于ArrayAccess您将通过$obj->property而不是访问属性$obj[offset]

于 2012-11-15T23:10:10.457 回答