(PECL ds >= 1.0.0)
Ds\Map::put — 将键与值关联
将一个 key 与一个 value 关联,如果已存在关联则覆盖之前的关联。
注意:
支持 对象类型的键。如果对象实现了 Ds\Hashable,则相等性将由对象的
equals函数确定。如果对象没有实现 Ds\Hashable,则对象必须是同一个实例的引用才能被认为是相等的。
注意:
您也可以使用数组语法通过键关联值,例如
$map["key"] = $value。
使用数组语法时要小心。标量键将被引擎强制转换为整数。例如,$map["1"] 将尝试访问 int(1),而 $map->get("1") 将正确查找字符串键。
参见 数组。
key要将值与其关联的键。
value要与键关联的值。
不返回任何值。
示例 #1 Ds\Map::put() 示例
<?php
$map = new \Ds\Map();
$map->put("a", 1);
$map->put("b", 2);
$map->put("c", 3);
print_r($map);
?>以上示例将输出类似于以下内容
Ds\Map Object
(
[0] => Ds\Pair Object
(
[key] => a
[value] => 1
)
[1] => Ds\Pair Object
(
[key] => b
[value] => 2
)
[2] => Ds\Pair Object
(
[key] => c
[value] => 3
)
)
示例 #2 使用对象作为键的 Ds\Map::put() 示例
<?php
class HashableObject implements \Ds\Hashable
{
/**
* 用作哈希值的任意值。不定义相等性。
*/
private $value;
public function __construct($value)
{
$this->value = $value;
}
public function hash()
{
return $this->value;
}
public function equals($obj): bool
{
return $this->value === $obj->value;
}
}
$map = new \Ds\Map();
$obj = new \ArrayIterator([]);
// 多次使用同一实例将覆盖先前的值。
$map->put($obj, 1);
$map->put($obj, 2);
// 使用同一对象的多个实例将创建新的关联。
$map->put(new \stdClass(), 3);
$map->put(new \stdClass(), 4);
// 使用多个相等的哈希对象的实例将覆盖先前的值。
$map->put(new \HashableObject(1), 5);
$map->put(new \HashableObject(1), 6);
$map->put(new \HashableObject(2), 7);
$map->put(new \HashableObject(2), 8);
var_dump($map);
?>以上示例将输出类似于以下内容
object(Ds\Map)#1 (5) {
[0]=>
object(Ds\Pair)#7 (2) {
["key"]=>
object(ArrayIterator)#2 (1) {
["storage":"ArrayIterator":private]=>
array(0) {
}
}
["value"]=>
int(2)
}
[1]=>
object(Ds\Pair)#8 (2) {
["key"]=>
object(stdClass)#3 (0) {
}
["value"]=>
int(3)
}
[2]=>
object(Ds\Pair)#9 (2) {
["key"]=>
object(stdClass)#4 (0) {
}
["value"]=>
int(4)
}
[3]=>
object(Ds\Pair)#10 (2) {
["key"]=>
object(HashableObject)#5 (1) {
["value":"HashableObject":private]=>
int(1)
}
["value"]=>
int(6)
}
[4]=>
object(Ds\Pair)#11 (2) {
["key"]=>
object(HashableObject)#6 (1) {
["value":"HashableObject":private]=>
int(2)
}
["value"]=>
int(8)
}
}