Ds\Map::put
(PECL ds >= 1.0.0)
Ds\Map::put — 将键与一个值关联。
描述
public void Ds\Map::put ( mixed $key , mixed $value )
将a key
与a联系起来value
,覆盖以前的联系(如果存在的话)。
注意:支持类型对象的键。如果一个对象实现了Ds \ Hashable,则等式将由该对象的
equals
函数决定。如果一个对象没有实现Ds \ Hashable,则对象必须是对同一个实例的引用才能被视为相等。
注意:您也可以使用数组语法通过键关联值,例如。
$map["key"] = $value
。
警告
使用数组语法时要小心。标量键将被引擎强制为整数。例如,$map["1"]
会尝试访问int(1)
,同时$map->get("1")
会正确查找字符串键。
见数组。
参数
key
把价值与价值联系起来的关键。
value
与密钥关联的值。
返回值
没有值返回。
Examples
示例#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
{
????/**
?????*?An?arbitrary?value?to?use?as?the?hash?value.?Does?not?define?equality.
?????*/
????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([]);
//?Using?the?same?instance?multiple?times?will?overwrite?the?previous?value.
$map->put($obj,?1);
$map->put($obj,?2);
//?Using?multiple?instances?of?the?same?object?will?create?new?associations.
$map->put(new?\stdClass(),?3);
$map->put(new?\stdClass(),?4);
//?Using?multiple?instances?of?equal?hashable?objects?will?overwrite?previous?values.
$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)
}
}
← Ds\Map::pairs
Ds\Map::putAll →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com