gpt4 book ai didi

PHP不需要属性?

转载 作者:行者123 更新时间:2023-12-04 05:24:07 25 4
gpt4 key购买 nike

通常使用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中的类不需要属性吗???

最佳答案

你的类(class)实现了 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]

关于PHP不需要属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com