able/struct

phpABLE struct 数据类型实现库

v1.1.1 2021-05-23 02:43 UTC

This package is auto-updated.

Last update: 2024-09-15 00:04:15 UTC


README

phpABLE struct 模拟库。

要求

特性

该库的使命是在最自然的方式下模拟结构的行为。

安装

通过 composer 安装 able/struct 包有一个简单的方法

composer require able/struct

使用

基本

让我们尝试声明一个结构

use \Able\Struct;

class MyStruct extends AStruct {

	protected static $Prototype = ['field1', 'field2'];
}

现在我们可以简单使用它

$Struct = new MyStruct(1,2);
echo $Struct->field1;

//> 1

也可以稍后填充字段

$Struct = new MyStruct();

$Struct->field1 = "Test string!";
echo $Struct->field1;

//> Test string!

修改器

如果需要自定义默认结构行为,修改器非常有帮助。

use \Able\Struct;

class MyStruct extends AStruct {

	protected static $Prototype = ['field1', 'field2'];
	
	protected final function setField1Property($value) {
		return 'The mutated via setter value is: ' . $value;
	}
	
	protected final function getField2Property($value) {
		return 'The mutated via getter value is: ' . $value;
	}
}

让我们测试它

$Struct = new MyStruct(1,2);

echo $Struct->field1;
echo $Struct->field2;

//> The mutated via setter value is: 1
//> The mutated via getter value is: 2

下一个例子仅说明了设置器和获取器之间的区别。

$Data = $Struct->toArray();

echo $Data['field1'];
echo $Data['field2'];

//> The mutated via setter value is: 1
//> 2

默认值

可以通过常量设置默认值。

use \Able\Struct;

class MyParentStruct extends AStruct {

	protected static array $Prototype = ['field1', 'field2'];
	
	protected const defaultField1Value = "default value for field1";
	protected const defaultField2Value = "default value for field2";
}

继承

继承级别不受限制。父类中定义的所有字段在子类中也可访问。

use \Able\Struct;

class MyParentStruct extends AStruct {

	protected static array $Prototype = ['field1', 'field2'];
}

class MyChildStruct extends MyParentStruct {

	protected static array $Prototype = ['field3'];
}

它完美地工作

$Struct = new MyChildStruct(1,2,3);

echo $Struct->field1;
echo $Struct->field2;
echo $Struct->field3;

//> 1
//> 2
//> 3

高级

检索所有结构键

$Struct->keys();

检索所有结构值

$Struct->values();

将所有数据复制到数组中

$Struct->toArray();

获取字段数量

$Struct->count();

清除所有字段并恢复其默认值

$Struct->flush();

IDE 支持

如果你使用一个兼容 PHPDoc 的 IDE,你可以通过使用以下语法获得额外的好处

use \Able\Struct;

/**
 * @property int field1
 * @property string field2
 */
class MyStruct extends AStruct {

	protected static array $Prototype = ['field1', 'field2'];
}

许可

此软件包在 MIT 许可证 下发布。