如何在PHP中使用对象键创建类似数组的数据结构?

Car*_*son 5 php map data-structures

我想用PHP创建带有对象键的数组,即:

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

$hash = array($keyObject => $valueObject);
Run Code Online (Sandbox Code Playgroud)

但是,这会引发错误.数组可能只有整数或字符串键.我最终不得不这样做:

$hash = array(
    'key'   => $keyObject,
    'value' => $valueObject);
Run Code Online (Sandbox Code Playgroud)

这有效,但它并不像我想的那样整洁.有没有更好的办法?(也许是我失踪的SPL的东西......)

TIA

Ben*_*mes 10

您可以使用SplObjectStorageSPL作为带有对象键的地图:

$map = new SplObjectStorage;
$key = new StdClass;
$value = new StdClass;
$map[$key] = $value;
Run Code Online (Sandbox Code Playgroud)