Anonymous Objects in PHP

A little known but often useful feature of PHP’s object oriented functionality is anonymous objects which are generally used as value stores. Here’s an example:

$valueStore = (object) array(
    'name' => 'John Smith',
    'address' => array(
        '1 Some Street',
        'Some Town, Post Code',
        'Ireland'
    )
);

If you were to dump the resultant object, you’d get:

object(stdClass)#1 (2) {
    ["name"] => string(10) "John Smith"
    ["address"] => array(3) {
        [0] => string(13) "1 Some Street"
        [1] => string(20) "Some Town, Post Code"
        [2] => string(7) "Ireland"
    }
}

You can now add new items ($valueStore->item = 'qwerty'), check is items are set (isset()), remove items (unset()), and retrieve items ($valueStore->item).

But why? Well, a reason I use these anonymous objects for frequently is when I need to pass around a value store between different functions, objects, registries and so forth. With standard arrays, these are passed by value meaning you are making copies but also that changes on one won’t affect another.

If we use anonymous objects then these are passed by reference and no copies are created. We could use the reference operator I hear you scream. Yes, we could. But that is more prone to forgetful errors and is not as elegant as the above!

If you want to take it further, you can add functionality via anonymous functions and closures.