Zend PHP 7 Certification – OOP – SPL

This post covers the SPL section of the OOP chapter when studying for the Zend PHP 7 Certification.

SPL, or Standard PHP Library, is a collection of interfaces and classes that are meant to solve common problems without having to install any external libraries. The library is available and compiled by default in PHP 5.

As seen in the Autoload section, the SPL library provides a spl_autoload_register() function.

One of the classes included in the library is the ArrayIterator class.

This class allows you to unset and modify values and keys while iterating over Arrays and Objects. For example, we can pass an array within the ArrayIterator class

<?php
$fruits = array(
    "apple" => "An apple",
    "orange" => "An orange",
    "grape" => "A grape",
    "plum" => "A plum"
);

$obj = new ArrayIterator($fruits);

// How many items are we iterating over?
echo "Iterating over: " . $obj->count() . " values\n";

// Outputs:
Iterating over: 4 values

Other functions are available in the class such as serialize():

echo $obj->serialize();

// Outputs:
x:i:0;a:4:{s:5:"apple";s:5:"An apple";s:6:"orange";s:11:"An orange";s:5:"grape";s:15:"A grape";s:4:"plum";s:11:"A plum";};m:a:0:{}

So when would be ideal to use the SPL using classes such as the ArrayIterator class rather than the standard array functions that are present?

One of the big advantages of the SPL is that the PHP foreach function makes a copy of any array passed to it. If you are processing a large amount of data, having the large arrays copied each time you use them in a foreach loop could affect performance.

SPL iterators encapsulate the list and expose visibility to one element at a time making them far more efficient.

<?php
$fruits = array(
    "apple" => "An apple",
    "orange" => "An orange",
    "grape" => "A grape",
    "plum" => "A plum"
);

$obj = new ArrayIterator($fruits);

foreach ($obj as $key => $value) {
    echo $key . ": " . $value . "\n";
}

// Outputs:
apple: An apple
orange: An orange
grape: A grape
plum: A plum

Note that you can also use the ArrayObject class to achieve the same result.

$fruits = array(
    "apple" => "An apple",
    "orange" => "An orange",
    "grape" => "A grape",
    "plum" => "A plum"
);
$obj = new ArrayObject( $fruits );

foreach ($obj as $key => $value) {
    echo $key . ": " . $value . "\n";
}

// Also outputs:
apple: An apple
orange: An orange
grape: A grape
plum: A plum

This is because in the __construct() function of the ArrayObject class, the $iterator_class argument is ArrayIterator by default.

public function __construct($input = null, $flags = 0, $iterator_class = "ArrayIterator"){}

Other classes in the SPL include:

  • CachingIterator
  • DirectoryIterator
  • RecursiveArrayIterator
  • RegexIterator

View the other sections:

Note: This article is based on PHP version 7.0.