Skip to content

Instantly share code, notes, and snippets.

@hirak
Created February 20, 2014 15:11
Show Gist options
  • Save hirak/9115844 to your computer and use it in GitHub Desktop.
Save hirak/9115844 to your computer and use it in GitHub Desktop.
SplFixedArrayで"純粋な配列"を作る ref: http://qiita.com/Hiraku/items/471747cacda58070f3a6
<?php
$a1 = [10,20,30]; //配列っぽい配列
$a2 = [2=>10, 0=>20, 1=>30]; //添え字は整数だが順番が変な配列
$a3 = ['a'=>10, 20, 30]; //添え字に文字列が混じってる
<?php
/**
* 純粋な配列
*
*/
class Collection extends SplFixedArray
{
function offsetSet($offset, $value)
{
if ($offset === null) {
$offset = count($this);
$this->setSize($offset + 1);
}
//配列要素の型を固定にしたければ、ここで$valueの型をチェックすればよい
return parent::offsetSet($offset, $value);
}
}
<?php
$a1 = new Collection;
$a1[] = 10;
$a1[] = 20;
$a1[] = 30;
//$a1['a'] = 'hoge'; //例外が発生して止まる
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment