PHPマニュアル/PEARマニュアル | ユーザフォーラムで議論/質問 | マニュアル検索 | ハイライト | ハイライトオフ | ポータル | php spot

Ds\Set::add - Adds values to the set. | JavaScript入門&応用&リファレンスなら「JavaScriptist」

  

Ds\Set::add

(PECL ds >= 1.0.0)

Ds\Set::addAdds values to the set.

説明

public void Ds\Set::add ([ mixed $...values ] )

Adds all given values to the set that haven't already been added.

注意:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

警告

All comparisons are strict (type and value).

パラメータ

values

Values to add to the set.

返り値

値を返しません。

例1 Ds\Set::add() example using integers

<?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() example using objects

<?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)
  }
}

忘却曲線を使ってこの知識を確実に記憶に残す

フォーラムで「Ds\Set::add - Adds values to the set.」について話す
各種マニュアル: PHPマニュアル | PEARマニュアル | Smarty(英語)マニュアル | PHP-GTKマニュアル | Ds\Set::add - Adds values to the set.」をGoogle検索
copyright © 1997-2024 PHP ドキュメント作成グループ(ライセンス). provided by php spot. マニュアル: