Attempt to use ArrayObject as unified array

The problem was following in different part of my application we have to pass array of DNS. The problem that in one place it looks like that

array(‘ns1’ => ‘’, ‘ns2’ => ‘’,’addr1′ => ‘’, ‘addr2’ => ‘’, .. ‘ns6’ => ”)
in other
array(1 => array(‘ns’ => ‘’, ‘addr’ = ‘’), 2 => array(…), .. 6 => array(..) )
and others variations.

and it was quite confusing cause every time you have to check which variant of array you will get. It has been already beig volume of code using this. And I didn’t want to change it. So I started to think about class that could replace array. I want to implement __get __set start working with that mess and after half and hour I finally came to ArrayObject SPL class.

It seemed to me a very good solution. Cause all I’ve done was that


 * Structure class to unify nses array
 * User: radzserg
 * Date: 6/26/12
class Struct_Nses extends ArrayObject

    public function offsetSet($name, $value)
        return parent::offsetSet($name, $value);

    private function _checkName($name)
        $availableNames = array('ns1', 'ns2', 'ns3', 'ns4', 'ns5', 'ns6',
            'addr1', 'addr2', 'addr3', 'addr4', 'addr5', 'addr6',
        if (!in_array($name, $availableNames)) {
            throw new Exception("Undefined name {$name} for Struct_Nses");


It was an array that can check keys. Also I can check other errors like Stuct_Nses at least should have 2 nses, check ns format and others.

And everything was good until I ran tests. Epic fail 🙂 This is an object not an array. All operations like this

$nses = Struct_Nses()

$nses[‘ns1’] = ‘’;

$nses += array(‘ns2’ => ‘’) or array_merge($nses, array(‘’))

fail. Unfortunately I have to refuse of this cause I have to change a lot of important and working code.

But this is really cool feature and I think I’ll use such approach in future.

Leave a Reply

Your email address will not be published. Required fields are marked *