(PECL ds >= 1.0.0)
Ds\Map::put — 將鍵與值關聯
將 key
與 value
關聯,如果先前存在關聯,則覆寫先前的關聯。
注意:
支援 object 類型的鍵。如果物件實作了 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) } }