Home arrow PHP arrow ArrayObject PHP Class: An Introduction

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.

TABLE OF CONTENTS:
  1. ArrayObject PHP Class: An Introduction
  2. Handling Properties As Array Elements
By: Alejandro Gervasio
Rating: starstarstarstarstar / 0
November 16, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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(ArrayObject\User1)#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.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: