php - An object that can be used as an array as well -
all on place have array few elements, example:
$myitem = [ 'a' => 10, 'b' => 20 ] but replace class
$myclass = new myownclass( 10, 20 );
$a = $myclass->getsomevalue(); // old 'a' $b = $myclass->getsomeothervalue(); // old 'b' but practical reasons still want able call
$a = $myclass['a']; $b = $myclass['b']; is possible in php?
therefore, there interface named arrayaccess. have implement 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
Comments
Post a Comment