views:

59

answers:

1

I want create arrays with object keys in PHP, i.e. something like this:

<?php
$keyObject   = new KeyObject;
$valueObject = new ValueObject;

$hash = array($keyObject => $valueObject);

However, this raises an error. Arrays may only have integer or string keys. I end up having to do something like:

$hash = array(
    'key'   => $keyObject,
    'value' => $valueObject);

This works but it's not as neat as I'd like. Is there a better way? (Perhaps something from the SPL that I'm missing...)

TIA

+4  A: 

You can use SplObjectStorage from the SPL as a map with object keys:

$map = new SplObjectStorage;
$key = new StdClass;
$value = new StdClass;
$map[$key] = $value;
Ben James
Brilliant. Thank you!
Carlton Gibson