Ds\Set::add
(PECL ds >= 1.0.0)
Ds \ Set :: add - 将值添加到集合中。
描述
public void Ds\Set::add ([ mixed $...values ] )
将所有给定值添加到尚未添加的集合中。
注意:支持类型对象值。如果一个对象实现了Ds \ Hashable,则等式将由该对象的
equals
函数决定。如果一个对象没有实现Ds \ Hashable,则对象必须是对同一个实例的引用才能被视为相等。
警告
所有比较都是严格执行的(类型和价值)。
参数
values
要添加到集合中的值。
返回值
没有返回值。
示例
示例#1使用整数Ds \ Set :: add()示例
<?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);
?>
上面的例子会输出如下信息:
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()示例
<?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);
?>
上面的例子会输出如下信息:
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 →
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com