ArrayObject PHP Class: An Introduction

In this first part of a two-part tutorial, I demonstrate how simple it is to use the ArrayObject SPL class. This class permits you to easily access properties through an array syntax.

Added to PHP5 and improved in successive releases, the Standard PHP Library (SPL) is one of those things that, once you’ve used it, makes you wonder how you could live so long (and so painfully) without it. The library provides, right out the box, a set of native interfaces and classes which allow you to perform different tasks, without having to enter "userland."

While the SPL’s core functionality is unquestionably hard to beat, sometimes it’s a little overwhelming; it includes so many classes, and some of them have been assigned some strange names (especially the native iterators). All jokes aside, the truth is that some people feel a bit reluctant to explore the SPL in depth; thus, they miss some “goodies” hidden in the library.

A glaring example of this is the ArrayObject class. This class is an iteratable and countable structure which makes it possible to treat objects as arrays. In fact, ArrayObject has spread to several popular frameworks and libraries. The class is flexible enough to be used as a multipurpose base implementation, which in most cases is refined via Inheritance.

Despite this, it remains as an overlooked SPL component that deserves a closer analysis. Therefore, in this two-part tutorial I’ll be creating some examples to show you how to get things rolling with the ArrayObject class (at least at a basic level), and how to put it to work in a pretty realistic use case.

Now that we’re doing with the preliminaries, let’s get to work.

ArrayObject Class: Assigning Properties, Looping and More

As I noted in the introduction, one of ArrayObject’s virtues is its flexibility, as it will let you pass to its constructor either an array of values which are stored in private properties, or an object.

To make things easier to follow, let me show you how to take the first path. In the simplest use case, creating an instance of the class, and injecting a trivial array into the constructor can be accomplished in the following way (the specification of a namespace is, of course, optional):

<?php

namespace ArrayObject;

$data = array(
    ‘name’  => ‘John Doe’,
    ‘email’ => ‘john@domain.com’
);

// create an instance of the ArrayObject class
$arrayObj = new ArrayObject($data);

Definitely, not much needs to be said about the above snippet, as it speaks for itself. So, let’s move on and see how easy it is to manipulate the data just passed to the ArrayObject.

The code fragment below does exactly that. Check it out:

// access the object properties using an array notation
echo ‘Full name: ‘ . $arrayObj['name'] . ‘ Email: ‘ . $arrayObj['email'];
// displays the following: Full name: John Doe Email: john@domain.com

// count the number of properties in the object
echo ‘Number of properties assigned to the object: ‘ . count($arrayObj);
// displays the following: Number of properties assigned to the object: 2

// dump the array object
var_dump($arrayObj);
/* displays the following

object(ArrayObject)#1 (1) { ["storage":"ArrayObject":private]=> array(2) { ["name"]=> string(8) "John Doe" ["email"]=> string(15) "john@domain.com" } }

// put the array object in a foreach loop
foreach ($arrayObj as $key => $value) {
    echo ‘Key: ‘ . $key . ‘ Value: ‘ . $value . ‘<br />';
}
/* displays the following

Key: name Value: John Doe
Key: email Value: john@domain.com

*/

Now, things are getting a bit more interesting. As you can see, it’s simple to retrieve and count the properties assigned to the ArrayObject, as well as and traverse the object through a “foreach” loop. It’s also possible to feed the object in question another one, by passing it to the constructor.

If you’re curious and want to see how to do that, simply look at the following code fragment. It defines a contrived “User” class: 

(User.php)

<?php

namespace ArrayObject;

class User
{
    public $_name;
    public $_email;
   
    /**
     * Constructor
     */
    public function __construct($name, $email)
    {
        $this->_name = $name;
        $this->_email = $email;
    }
   
    /**
     * Get the user’s name
     */
    public function getName()
    {
        return $this->_name;
    }
   
    /**
     * Get the user’s email
     */
    public function getEmail()
    {
        return $this->_email;
    }       
}

With this sample class already set (notice that its properties have been deliberately declared public), it’s really simple to pass an instance of it to the constructor of the ArrayObject and perform the same tasks that you saw in the earlier array-based example. Again, be sure to check the following snippet: 

<?php


namespace ArrayObject;

require_once ‘User.php';

// create an instance of the User class
$user = new User(‘John Doe’, ‘john@domain.com’);

// create an instance of the ArrayObject class
$arrayObj = new ArrayObject($user);

// access the object properties using an array notation
echo ‘Full name: ‘ . $arrayObj['_name'] . ‘ Email: ‘ . $arrayObj['_email'];
// displays the following: Full name: John Doe Email: john@domain.com

// count the number of properties in the object
echo ‘Number of properties assigned to the object: ‘ . count($arrayObj);
// displays the following: Number of properties assigned to the object: 2

// dump the array object
var_dump($arrayObj);
/* displays the following

bject(ArrayObject)#2 (1) { ["storage":"ArrayObject":private]=> object(ArrayObjectUser1)#1 (2) { ["_name"]=> string(8) "John Doe" ["_email"]=> string(15) "john@domain.com" } }

*/
// put the array object in a foreach loop
foreach ($arrayObj as $key => $value) {
    echo ‘Key: ‘ . $key . ‘ Value: ‘ . $value . ‘<br />';
}
/* displays the following

Key: _name Value: John Doe
Key: _email Value: john@domain.com

*/

That was pretty easy to grasp, wasn’t it? In this case, the properties of the “User” class remained accessible to the ArrayObject, as they were defined public, thus making it possible to count them, drop them into a “foreach” loop and so forth. If they were protected or private, though, the object wouldn’t be able to retrieve them, and consequently, the PHP interpreter would trigger a few ugly notices. Just try this for yourself to grasp in a snap the inner workings of this process.

{mospagebreak title=Handling Properties As Array Elements}

I’m pretty sure that you now know how to do simple things with the ArrayObject class, like assigning some properties to it which can be manipulated via an array notation. It’s valid to point out that the class allows you to treat the properties using an object-oriented syntax by passing an additional constant (or flag) called ARRAY_AS_PROPS to the class’s constructor.  

This scenario will be covered in the second part of this tutorial. However, if you’re wondering how the object currently handles the properties as if they were array elements, the answer is simple: it uses by default a flag named STD_PROP_LIST, which gives the class this array-like feeling.

Given that, the first example could be rewritten as follows:

<?php

namespace ArrayObject;

$data = array(
    ‘name’  => ‘John Doe’,
    ‘email’ => ‘john@domain.com’
);

// create an instance of the ArrayObject class
$arrayObj = new ArrayObject($data, ArrayObject::STD_PROP_LIST);

// access the object properties using an array notation
echo ‘Full name: ‘ . $arrayObj['name'] . ‘ Email: ‘ . $arrayObj['email'];
// displays the following: Full name: John Doe Email: john@domain.com

// count the number of properties in the object
echo ‘Number of properties assigned to the object: ‘ . count($arrayObj);
// displays the following: Number of properties assigned to the object: 2

// dump the array object
var_dump($arrayObj);
/* displays the following

object(ArrayObject)#1 (1) { ["storage":"ArrayObject":private]=> array(2) { ["name"]=> string(8) "John Doe" ["email"]=> string(15) "john@domain.com" } }

*/
// put the array object in a foreach loop
foreach ($arrayObj as $key => $value) {
    echo ‘Key: ‘ . $key . ‘ Value: ‘ . $value . ‘<br />';
}
/* displays the following

Key: name Value: John Doe
Key: email Value: john@domain.com

*/

As I just explained, the ArrayObject’s default behavior is controlled by the STD_PROP_LIST constant, which allows properties to be manipulated as common array elements. Of course, it’s possible to assign those properties after the object has been created, as shown by the following code snippet:

<?php

namespace ArrayObject;

$data = array(
    ‘name’  => ‘John Doe’,
    ‘email’ => ‘john@domain.com’
);

// create an instance of the ArrayObject class
$arrayObj = new ArrayObject;
$arrayObj->setFlags(ArrayObject::STD_PROP_LIST);

$arrayObj['name'] = ‘John Doe';
$arrayObj['email'] = ‘john@domain.com';

// access the object properties using an array notation
echo ‘Full name: ‘ . $arrayObj['name'] . ‘ Email: ‘ . $arrayObj['email'];
// displays the following: Full name: John Doe Email: john@domain.com

// count the number of properties in the object
echo ‘Number of properties assigned to the object: ‘ . count($arrayObj);
// displays the following: Number of properties assigned to the object: 2 
   
There you have it. At this point, you should have a clearer idea of how to use the ArrayObject SPL class to perform a few basic tasks. Unfortunately, its major drawback is that it can’t be used with most of the built-in PHP functions. Sad but true.

Regardless, it’s fairly simple to recreate part of this functionality via custom implementations. A clear example of this is the Zend_Registry component, which is a subclass of ArrayObject (http://framework.zend.com/manual/en/zend.registry.using.html). Therefore, if you found the class’s functionality appealing enough, you might want to further extend it by using Inheritance.

Closing Remarks

In this introductory part of a two-part tutorial, I developed a few approachable examples to show you how simple it is to get things up and running with the ArrayObject SPL class. As I stated previously, it permits you to easily access properties through an array syntax. It’s also feasible to change this behavior and make it treat the pertinent properties using an object notation.

That’s precisely the topic that I’ll be discussing in detail in the last installment. You won’t want to miss it.

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan