표준 PHP 라이브러리(SPL) SplFixedArray class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)


소개

SplFixedArray 클래스는 배열의 주요 기능을 제공합니다. SplFixedArray와 일반 PHP 배열의 주요 차이점은 SplFixedArray의 크기를 수동으로 조정해야 하며 범위 내의 정수만 인덱스로 허용한다는 것입니다. 장점은 표준 배열보다 적은 메모리를 사용한다는 것입니다.


클래스 개요

                  
class SplFixedArray implements IteratorAggregate, ArrayAccess, Countable, JsonSerializable {

  /* Methods */
  public __construct(int $size = 0)
  public count(): int
  public current(): mixed
  public static fromArray(array $array, bool $preserveKeys = true): SplFixedArray
  public getSize(): int
  public key(): int
  public next(): void
  public offsetExists(int $index): bool
  public offsetGet(int $index): mixed
  public offsetSet(int $index, mixed $value): void
  public offsetUnset(int $index): void
  public rewind(): void
  public setSize(int $size): bool
  public toArray(): array
  public valid(): bool
  public __wakeup(): void
}
                  
                

변경 로그

버전 설명
8.1.0 SplFixedArray는 이제 JsonSerializable을 구현합니다.
8.0.0 SplFixedArray는 이제 IteratorAggregate를 구현합니다. 이전에는 Iterator가 대신 구현되었습니다.

Examples

예제 #1 SplFixedArray 사용 예

                  
<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
    var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[-1]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[5]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}
?>
                  
                

위의 예는 다음을 출력합니다.

NULL
int(2)
string(3) "foo"
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
                

목차