Reputation: 1257
All over the place I have an array with a few elements, for example:
$myItem = [ 'a' => 10, 'b' => 20 ]
But but I would like to replace it with a class
$myClass = new MyOwnClass( 10, 20 );
$a = $myClass->GetSomeValue(); // this is the old 'a'
$b = $myClass->GetSomeOtherValue(); // this is the old 'b'
but for practical reasons I still want to be able to call
$a = $myClass['a'];
$b = $myClass['b'];
Is something like that possible in php?
Upvotes: 2
Views: 48
Reputation: 2815
Therefore, there is an interface named ArrayAccess. You have to implement it to your class.
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]);
}
}
Use:
$arr = ["a" => 20, "b" => 30];
$obj = new MyOwnClass($arr);
$obj->offsetGet("a"); // Gives 20
$obj->offsetSet("b", 10);
$obj->offsetGet("b"); // Gives 10
Upvotes: 2