# PHP SPL (Standard PHP Library)

The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve common problems. It provides a set of standard data structures, iterators, and other tools.

SPL is a core part of PHP and is enabled by default.

## Data Structures

SPL provides a set of object-oriented data structures that can be used to store and manipulate data. These are often more efficient and powerful than simple PHP arrays.

-   `SplDoublyLinkedList`: A doubly linked list.
-   `SplStack`: A stack (LIFO - Last In, First Out).
-   `SplQueue`: A queue (FIFO - First In, First Out).
-   `SplHeap`, `SplMinHeap`, `SplMaxHeap`: Different types of heaps.
-   `SplPriorityQueue`: A queue that orders elements by priority.
-   `SplFixedArray`: A fixed-size array, which can be faster than a regular PHP array in some cases.
-   `SplObjectStorage`: A map that uses objects as keys.

```php
<?php
$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');

$list->rewind();
while($list->valid()){
    echo $list->current() . "\n";
    $list->next();
}
?>
```

## Iterators

SPL provides a set of iterators that can be used to traverse over data structures. Many of the built-in SPL data structures, as well as regular PHP arrays, can be used with these iterators.

-   `ArrayIterator`: Iterates over an array.
-   `AppendIterator`: Iterates over several iterators one after another.
-   `CachingIterator`: Caches the current and next elements of an iterator.
-   `FilterIterator`: Filters an iterator based on a predicate.
-   `LimitIterator`: Limits the number of items in an iterator.
-   `RecursiveIteratorIterator`: Used to iterate over a recursive iterator.

## Interfaces

SPL also defines a set of interfaces that allow your own classes to behave like data structures.

-   `Traversable`: The base interface for all traversable classes. You can't implement this directly; instead, you implement `Iterator` or `IteratorAggregate`.
-   `Iterator`: For classes that can be iterated over. Requires methods like `current()`, `key()`, `next()`, `rewind()`, and `valid()`.
-   `IteratorAggregate`: A simpler alternative to `Iterator`. Requires a single method `getIterator()` that returns an `Iterator`.
-   `Countable`: For classes that can be counted with the `count()` function.
-   `ArrayAccess`: Allows an object to be accessed like an array.

## Autoloading

Before Composer became the standard, SPL provided the `spl_autoload_register()` function, which is still the foundation of modern autoloading in PHP. It allows you to register multiple functions that PHP will call when it tries to use a class that hasn't been defined yet.

```