首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Ds\Map::put

(PECL ds >= 1.0.0)

Ds\Map::put — 将键与一个值关联。

描述

代码语言:javascript
复制
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() 示例

代码语言:javascript
复制
<?php
$map = new \Ds\Map();

$map->put("a", 1);
$map->put("b", 2);
$map->put("c", 3);

print_r($map);
?>

上面的例子会输出类似于:

代码语言:javascript
复制
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()示例

代码语言:javascript
复制
<?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);
?>

上面的例子会输出类似于:

代码语言:javascript
复制
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 →

扫码关注腾讯云开发者

领取腾讯云代金券