digitick / collection
开发者用集合工具
v2.0.0
2023-11-23 10:12 UTC
Requires
- php: ^8.0
Requires (Dev)
- phpunit/phpunit: ^9.0||^10.0
This package is not auto-updated.
Last update: 2024-09-10 19:59:36 UTC
README
集合管理类
类图
使用方法
列出集合
列表集合以一种有序的方式存储一系列项目。
基本列表
接受任何类型项目的列表。
$size = 4; $list = new BaseList($size); $list->set (0, "First item"); // Setter style $list[1] = 123; // Array style foreach ($list as $item) { echo $item; }
类型列表
您可以定义一个列表,它只包含您想要的类的项目。集合确保类型检查。
<?php require __DIR__ . "/vendor/autoload.php"; // The class you want to be in your list collection class MyItem { public $value; /** * MyItem constructor. * @param $value */ public function __construct($value) { $this->value = $value; } /** * @return mixed */ public function getValue() { return $this->value; } /** * @param mixed $value * @return MyItem */ public function setValue($value) { $this->value = $value; return $this; } } // Declare your list collection for class MyItem class MyItemList extends \Digitick\Foundation\Collection\AbstractTypedList { /** * @var string */ protected static $CLASSORTYPENAME = "MyItem"; // Ensure that the list will only contains items of class MyItem } // You must give the size of your list $myList = new MyItemList (3); // You can access to your list like standard PHP array $myList [0] = new MyItem(1); $myList [1] = new MyItem(2); $myList [2] = new MyItem(3); // Except for this syntax : new values can not be pushed at the end of the list; //$myList [] = new MyItem(3); // Throw exception // You can iterate over your list with foreach syntax /** @var MyItem $item */ foreach ($myList as $item) { echo "Item : " . $item->getValue() . "\n"; }
整数列表
预定义的整数类型列表。
$list = new IntList($size); $list->set (0, 123); // Setter style $list[1] = 123; // Array style $list[2] = "foo"; // throw exception
字符串列表
预定义的字符串类型列表。
$names = new \Digitick\Foundation\Collection\StringList(2); $names [0] = "Emilio Bradshaw"; $names [1] = "Dyler Runner";
集合集合
与列表集合不同,集合集合中的元素是无序的。
$lottery = new \Digitick\Foundation\Collection\IntScalarSet(10); for ($i = 0; $i < 10; $i++) { $randomNumber = rand (1, 10); echo "Add $randomNumber\n"; $lottery->add($randomNumber); } if ($lottery->contains(5)) { echo "Number 5 exists : WIN !"; } else { echo "Number 5 is elsewhere: LOOSE !"; }
类型集合
类似于列表集合,集合可以被限制为特定类型/类。
class CustomType { } class CustomTypeSet extends \Digitick\Foundation\Collection\AbstractTypedObjectSet { /** * @var string */ protected static $CLASSORTYPENAME = 'CustomType'; } $customSet = new CustomTypeSet(); $customSet->add (new CustomType());