Skip to content

Commit

Permalink
Iterator を実装した。これで foreach が使える。
Browse files Browse the repository at this point in the history
  • Loading branch information
yoya committed Oct 12, 2015
1 parent 77c838d commit db05a27
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
20 changes: 19 additions & 1 deletion Array/Typed.php
Expand Up @@ -5,13 +5,15 @@
Array_Typed version 1.0.3
*/

abstract class Array_Typed implements ArrayAccess, Countable {
abstract class Array_Typed implements ArrayAccess, Countable, Iterator {
protected $container;
protected $arraySize;
private $iterPos;
// protected $typeSize;
function __construct($n) {
$this->arraySize = $n;
$this->container = str_repeat("\0", $n * $this->typeSize);
$this->iterPos = 0;
}
//
function toArray() {
Expand All @@ -37,6 +39,22 @@ public function getSize() {
public function count() {
return $this->arraySize;
}
// Iterator
public function rewind() {
$this->iterPos = 0;
}
public function current() {
return $this->_offsetGet($this->iterPos);
}
public function key() {
return $this->iterPos;
}
function next() {
$this->iterPos++;
}
function valid() {
return $this->offsetExists($this->iterPos);
}
//
public function offsetExists($offset) {
if (($offset < 0) || ($this->arraySize <= $offset)) {
Expand Down
32 changes: 32 additions & 0 deletions test/iter_test.php
@@ -0,0 +1,32 @@
<?php

if (is_readable('vendor/autoload.php')) {
require 'vendor/autoload.php';
} else {
require_once 'Array/Sint8.php';
}

echo "Array_Sint8(0)".PHP_EOL;
$arr = new Array_Sint8(0);
foreach ($arr as $e) {
var_dump($e);
}
echo "Array_Sint8(7)".PHP_EOL;
$arr = new Array_Sint8(7);
foreach ($arr as $e) {
var_dump($e);
}


$a = array_pad([], 10, 0);
$a[0] = -1;
$a[8] = -8;
$a[9] = 9;
echo "Array_Sint8::fromArray".PHP_EOL;
$arr = Array_Sint8::fromArray($a);
foreach ($arr as $e) {
var_dump($e);
}
foreach ($arr as $e) {
var_dump($e);
}

0 comments on commit db05a27

Please sign in to comment.