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

Ds\Set::add

(PECL ds >= 1.0.0)

Ds \ Set :: add - 将值添加到集合中。

描述

代码语言:javascript
复制
public void Ds\Set::add ([ mixed $...values ] )

将所有给定值添加到尚未添加的集合中。

注意:支持类型对象值。如果一个对象实现了Ds \ Hashable,则等式将由该对象的equals函数决定。如果一个对象没有实现Ds \ Hashable,则对象必须是对同一个实例的引用才能被视为相等。

警告

所有比较都是严格执行的(类型和价值)。

参数

values

要添加到集合中的值。

返回值

没有返回值。

示例

示例#1使用整数Ds \ Set :: add()示例

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

$set->add(1);
$set->add(1);
$set->add(2);
$set->add(3);

// Strict comparison would not treat these the same as int(1)
$set->add("1");
$set->add(true);

var_dump($set);
?>

上面的例子会输出如下信息:

代码语言:javascript
复制
object(Ds\Set)#1 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  string(1) "1"
  [4]=>
  bool(true)
}

示例#2使用对象的Ds \ Set :: add()示例

代码语言: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;
    }
}

$set = new \Ds\Set();

$obj = new \ArrayIterator([]);

// Adding the same instance multiple times will only add the first.
$set->add($obj);
$set->add($obj);

// Adding multiple instances of the same object will add them all.
$set->add(new \stdClass());
$set->add(new \stdClass());

// Adding multiple instances of equal hashable objects will only add the first.
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(2));
$set->add(new \HashableObject(2));

var_dump($set);
?>

上面的例子会输出如下信息:

代码语言:javascript
复制
object(Ds\Set)#1 (5) {
  [0]=>
  object(ArrayIterator)#2 (1) {
    ["storage":"ArrayIterator":private]=>
    array(0) {
    }
  }
  [1]=>
  object(stdClass)#3 (0) {
  }
  [2]=>
  object(stdClass)#4 (0) {
  }
  [3]=>
  object(HashableObject)#5 (1) {
    ["value":"HashableObject":private]=>
    int(1)
  }
  [4]=>
  object(HashableObject)#6 (1) {
    ["value":"HashableObject":private]=>
    int(2)
  }
}

← Set

Ds\Set::allocate →

扫码关注腾讯云开发者

领取腾讯云代金券