ngmy / typed-array
PHP 的类型化数组
0.11.0
2021-04-03 12:43 UTC
Requires
- php: ^7.3|^8.0
README
PHP Typed Array 是 PHP 的类型化数组。
- 可以创建具有指定键和值类型的类型化数组
- 可以指定 bool、float、int、object、resource 或 string 类型,或指定的类类型,或实现指定接口的类类型,或使用指定 trait 的类类型作为键类型
- 可以指定 array、bool、float、int、object、resource 或 string 类型,或指定的类类型,或实现指定接口的类类型,或使用指定 trait 的类类型作为值类型
- 实现了
ArrayAccess
、Countable
和IteratorAggregate
接口 - 支持 PHPStan 和 Psalm 等静态分析。请参阅 示例
// Returns a new instance of the typed array with the int type value $intArray = Ngmy\TypedArray\TypedArray::new()->withIntValue(); // TypedArray<mixed, int> $intArray[] = 1; // Good // $intArray[] = '2'; // No good. The InvalidArgumentException exception is thrown // Returns a new instance of the typed array with the class type value that implements the DateTimeInterface interface $dateTimeInterfaceArray = Ngmy\TypedArray\TypedArray::new() ->withInterfaceValue(DateTimeInterface::class); // TypedArray<mixed, DateTimeInterface> $dateTimeInterfaceArray[] = new DateTime(); // Good $dateTimeInterfaceArray[] = new DateTimeImmutable(); // Good // $dateTimeInterfaceArray[] = new stdClass(); // No good. The InvalidArgumentException exception is thrown foreach ($dateTimeInterfaceArray as $dateTime) { echo $dateTime->format('Y-m-d H:i:s') . PHP_EOL; } // Determines if the typed array is empty or not echo var_export($dateTimeInterfaceArray->isEmpty(), true) . PHP_EOL; // false // Gets the typed array of items as a plain array print_r($dateTimeInterfaceArray->toArray()); // Array // ( // [0] => DateTime Object // ... // [1] => DateTimeImmutable Object // ... // ) // You can also specify the type of the key $stringKeyArray = Ngmy\TypedArray\TypedArray::new()->withStringKey(); // TypedArray<string, mixed> $stringKeyArray['foo'] = 1; // Good // $stringKeyArray[] = 2; // No good. The InvalidArgumentException exception is thrown // Of course, you can also specify the type of both the key and the value $intStringArray = Ngmy\TypedArray\TypedArray::new()->withIntKey()->withStringValue(); // TypedArray<int, string>
要求
PHP Typed Array 有以下要求
- PHP >= 7.3
安装
执行 Composer 的 require
命令
composer require ngmy/typed-array
文档
请参阅 API 文档。
许可
PHP Typed Array 是开源软件,采用 MIT 许可协议。