note 94336 added to class.arrayaccess
| From: | Cintix at osu1 dot php dot net | Date: | Thu, 29 Oct 2009 09:32:19 +0000 |
| Subject: | note 94336 added to class.arrayaccess | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-162231@lists.php.net to get a copy of this message | ||
To take full advantages of all array features with ArrayAccess, then you would need to implements
Countable and Iterator
Like this.
<?php
class ArrayOfColorModel implements ArrayAccess, Iterator, Countable {
private $container = array();
public function __construct() {
}
public function offsetSet($offset,$value) {
if ($value instanceof ColorModel){
if ($offset == "") {
$this->container[] = $value;
}else {
$this->container[$offset] = $value;
}
} else {
throw new Exception("Value have to be a instance of the Model ColorModel");
}
}
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;
}
public function rewind() {
reset($this->container);
}
public function current() {
return current($this->container);
}
public function key() {
return key($this->container);
}
public function next() {
return next($this->container);
}
public function valid() {
return $this->current() !== false;
}
public function count() {
return count($this->container);
}
}
?>
Now you can using it like any other array.
<?php
$array = new ArrayOfColorModel();
foreach ($array as $model) {
var_export($model);
}
// OR
for($i=0;$i<count($array);$i++){
var_export($array[$i]);
}
?>
----
Server IP: 195.184.96.15
Probable Submitter: 195.189.232.33
----
Manual Page -- http://www.php.net/manual/en/class.arrayaccess.php
Edit -- https://master.php.net/note/edit/94336
Del: integrated -- https://master.php.net/note/delete/94336/integrated
Del: useless -- https://master.php.net/note/delete/94336/useless
Del: bad code -- https://master.php.net/note/delete/94336/bad+code
Del: spam -- https://master.php.net/note/delete/94336/spam
Del: non-english -- https://master.php.net/note/delete/94336/non-english
Del: in docs -- https://master.php.net/note/delete/94336/in+docs
Del: other reasons-- https://master.php.net/note/delete/94336
Reject -- https://master.php.net/note/reject/94336
Search -- https://master.php.net/manage/user-notes.php