La classe SplFixedArray

(PHP 5 >= 5.3.0, PHP 7)

Introduction

La classe SplFixedArray fournit les fonctionnalités principales d'un tableau. La différence majeure entre un objet SplFixedArray et un tableau standard de PHP est que SplFixedArray est de taille fixe, et n'utilise que des entier dans ses index. L'avantage est alors qu'il est plus rapide que les tableaux.

Synopsis de la classe

SplFixedArray implements Iterator , ArrayAccess , Countable {
/* Méthodes */
public __construct ([ int $size = 0 ] )
public count ( void ) : int
public current ( void ) : mixed
public static fromArray ( array $array [, bool $save_indexes = TRUE ] ) : SplFixedArray
public getSize ( void ) : int
public key ( void ) : int
public next ( void ) : void
public offsetExists ( int $index ) : bool
public offsetGet ( int $index ) : mixed
public offsetSet ( int $index , mixed $newval ) : void
public offsetUnset ( int $index ) : void
public rewind ( void ) : void
public setSize ( int $size ) : bool
public toArray ( void ) : array
public valid ( void ) : bool
public __wakeup ( void ) : void
}

Exemples

Exemple #1 Exemple avec SplFixedArray

<?php
// Initialisation d'un tableau avec une taille fixe
$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"

// Augmentation de la taille à 10
$array->setSize(10);

$array[9] = "asdf";

// Réduction de taille de 2
$array->setSize(2);

// Les lignes suivantes émettent une RuntimeException : index invalide ou hors de l'intervalle
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";
}
?>

L'exemple ci-dessus va afficher :

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

Sommaire