如何在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
答
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;