Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 12 ■ SPL ARRAY OVERLOADING^181

Listing 12-2. Using ArrayObject

$myArray = new ArrayObject();
$myArray['first'] = 'test';
$demo = $myArray['first'];
unset($myArray['first']);
$numElements = count($myArray);
foreach($myArray as $key=>$value) {}

You can use ArrayObject in many more advanced ways, including initializing it with the
values already contained within an array.
The ArrayObject class’s constructor method is defined as follows:

__construct ($array, $flags=0, $iterator_class="ArrayIterator")

The flags parameter can be one of two class constants:

•The ArrayObject::ARRAY_AS_PROPS constant makes all elements of the array additionally
become properties of the object.

•The ArrayObject::STD_PROP_LIST constant controls how properties are treated when
using listing functionality like var_dump, foreach, and so on.

The iterator class parameter controls which type of iterator is returned within the
IteratorAggregate implementation. This allows you to extend the object and provide your
own iteration class instead of the default ArrayIterator.

Table 12-2. ArrayObject Methods
Method Description
append($value) Allows you to add another element to the end of the list. It is syntac-
tically identical to using the [] array syntax.
asort() Applies the PHP asort() function to the underlying array values.
ksort() Sorts the array by key.
natcasesort() Sorts using the natural-order algorithm, case-insensitively.
natsort() Sorts using the natural-order algorithm, case-sensitively.
uasort($compare) Can be used to create a custom sorting routine. The $compare function
should be a function callback using the standard PHP callback syntax.
uksort($compare) Same as uasort(), but operates on keys rather than values.
getArrayCopy() Returns a copy of the underlying array.
exchangeArray($array) Allows you to change the underlying array, substituting another. It
can be used with getArrayCopy() to extract the information, modify
it, and repopulate the ArrayObject.

McArthur_819-9C12.fm Page 181 Thursday, February 28, 2008 7:51 AM

Free download pdf