Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

SplFixedArray

Reserva posições indexadas a partir de zero.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

new SplFixedArray($size)

Reserva posições indexadas a partir de zero. As posições não atribuídas contêm null e count mede a capacidade atual. setSize altera-a e ao reduzi-la descarta as posições finais. Um índice fora dos limites no PHP 8.4 lança OutOfBoundsException. O método SplFixedArray::offsetSet escreve numa posição atribuída e SplFixedArray::offsetGet lê o valor. O método SplFixedArray::count conta todas as posições, incluindo as com null, SplFixedArray::toArray devolve os valores num array normal e SplFixedArray::setSize altera o tamanho.

$a=new SplFixedArray(3); $a->offsetSet(1,"B"); $a->offsetSet(2,"C"); $initial=$a->toArray();
$a->setSize(2); echo json_encode([$initial,$a->count(),$a->toArray()]);
echo PHP_EOL,json_encode([$a->offsetGet(0),$a->offsetGet(1)]);
try{$x=$a->offsetGet(2);}catch(OutOfBoundsException $e){echo PHP_EOL,get_class($e);}
[[null,"B","C"],2,[null,"B"]]
[null,"B"]
OutOfBoundsException

Exemplos

<?php
$a=new SplFixedArray(3); $a->offsetSet(1,"B"); $a->offsetSet(2,"C"); $initial=$a->toArray();
$a->setSize(2); echo json_encode([$initial,$a->count(),$a->toArray()]);
echo PHP_EOL,json_encode([$a->offsetGet(0),$a->offsetGet(1)]);
try{$x=$a->offsetGet(2);}catch(OutOfBoundsException $e){echo PHP_EOL,get_class($e);}

Resultado

[[null,"B","C"],2,[null,"B"]]
[null,"B"]
OutOfBoundsException

Fontes