我到处都有一个包含几个元素的数组,例如:
$myItem = [ 'a' => 10, 'b' => 20 ]
但是我想用类替换它
$ myClass = new MyOwnClass(10,20);
$a = $myClass->GetSomeValue(); // this is the old 'a'
$b = $myClass->GetSomeOtherValue(); // this is the old 'b'
但出于实际原因,我仍然希望能够致电
$a = $myClass['a'];
$b = $myClass['b'];
在PHP中是否可以这样?
答案 0 :(得分:2)
因此,有一个名为ArrayAccess的接口。你必须把它实现到你的班级。
class MyOwnClass implements ArrayAccess {
private $arr = null;
public function __construct($arr = null) {
if(is_array($arr))
$this->arr = $arr;
else
$this->arr = [];
}
public function offsetExists ($offset) {
if($this->arr !== null && isset($this->arr[$offset]))
return true;
return false;
}
public function offsetGet ($offset) {
if($this->arr !== null && isset($this->arr[$offset]))
return $this->arr[$offset];
return false;
}
public function offsetSet ($offset, $value) {
$this->arr[$offset] = $value;
}
public function offsetUnset ($offset) {
unset($this->arr[$offset]);
}
}
使用:
$arr = ["a" => 20, "b" => 30];
$obj = new MyOwnClass($arr);
$obj->offsetGet("a"); // Gives 20
$obj->offsetSet("b", 10);
$obj->offsetGet("b"); // Gives 10