Carlton Gibson
Carlton Gibson

Reputation: 7386

How to create array-like data-structures with object keys in PHP?

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

Upvotes: 5

Views: 1153

Answers (1)

Ben James
Ben James

Reputation: 125167

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;

Upvotes: 10

Related Questions