Collection 接口

(PECL ds >= 1.0.0)

简介

Collection 是基本接口,涵盖了该库中所有数据结构的通用功能。它保证所有结构都是可遍历的、可计数的,并且可以使用 json_encode() 转换为 JSON。

接口概述

interface Ds\Collection extends Countable, IteratorAggregate, JsonSerializable {
/* 方法 */
public clear(): void
public isEmpty(): bool
public toArray(): array
/* 继承方法 */
}

变更日志

版本 描述
PECL ds 1.4.0 Collection 现在实现了 IteratorAggregate,而不是仅仅实现 Traversable。(此更改在 1.4.1 中加入了 polyfill。)

目录

添加说明

用户贡献的说明 1 个说明

depakin at yisangwu dot com
4 年前
// Collection
$collection_a = new \Ds\Vector([1, 2, 3]);
$collection_b = new \Ds\Vector();

var_dump($collection_a, $collection_b);
/*
object(Ds\Vector)[1]
public 0 => int 1
public 1 => int 2
public 2 => int 3

object(Ds\Vector)[2]
*/

//json_encode
var_dump( json_encode($collection_a));
/*
string '[1,2,3]
*/

//count
var_dump(count($collection_a));
/*
int 3
*/

// serialize
var_dump(serialize($collection_a));
/*
string 'C:9:"Ds\Vector":12:{i:1;i:2;i:3;}'
*/

// foreach
foreach ($collection_a as $key => $value) {
echo $key ,'--', $value, PHP_EOL;
}
/*
0--1
1--2
2--3
*/

// clone
$clone = clone($collection_a);
var_dump($clone);
/*
object(Ds\Vector)[1]
public 0 => int 1
public 1 => int 2
public 2 => int 3
*/

// push
$clone->push('aa');
var_dump($clone);
/*
object(Ds\Vector)[3]
public 0 => int 1
public 1 => int 2
public 2 => int 3
public 3 => string 'aa' (length=2)
*/

// isEmpty
var_dump($collection_a->isEmpty(), $collection_b->isEmpty());
/*
boolean false
boolean true
*/

// toArray
var_dump($collection_a->toArray(), $collection_b->toArray());
/*
array (size=3)
0 => int 1
1 => int 2
2 => int 3

array (size=0)
empty
*/

// copy ( void )
//浅拷贝, shallow copy
$collection_c = $collection_a->copy();

var_dump($collection_c);
/*
object(Ds\Vector)[3]
public 0 => int 1
public 1 => int 2
public 2 => int 3
*/

$collection_c->push(4);
var_dump($collection_a, $collection_c);
/*
object(Ds\Vector)[1]
public 0 => int 1
public 1 => int 2
public 2 => int 3

object(Ds\Vector)[3]
public 0 => int 1
public 1 => int 2
public 2 => int 3
public 3 => int 4
*/

// clear
$collection_a->clear();
$collection_b->clear();
$collection_c->clear();

var_dump($collection_a, $collection_b, $collection_c);
/*
object(Ds\Vector)[1]
object(Ds\Vector)[2]
object(Ds\Vector)[3]
*/
To Top