jumpifbelow/php-typed-array

为PHP添加类型化数组的库

2.1.0 2019-06-14 06:44 UTC

This package is auto-updated.

Last update: 2024-09-14 18:37:00 UTC


README

使PHP能够处理类型化数组

它做什么?

作为开发者,你可能想创建一个数组,但确信里面有什么。看起来很简单,在其他语言中也很熟悉,但在PHP中无法创建强类型数组。这个库试图解决这个问题,而且既快速又灵活。如果内置类型不够用,或者将类型设置为对象也不够,你可以创建自己的函数。它可以比仅仅类型更准确,例如只允许正整数。

如何使用它?

简单地将以下行添加到你的composer中

composer require jumpifbelow/php-typed-array

然后开始魔法之旅。

代码看起来像什么?

因为这个库非常简单,一些例子会比逐个写下所有方法要好得多,而不涉及任何逻辑。以下是一些工作示例,并进行了说明。

<?php
use TypedArray\TypedArray;

$t = new TypedArray(TypedArray::TYPE_INT);

$t[] = 5; // it is an int, everyting works great!
$t[] = 'str'; // hell no, it is a string, WrongValueException is thrown

现在,想象一下你想要设置一些类

<?php
use TypedArray\TypedArray;

class CustomClass extends stdClass {}
class InheritedClass extends CustomClass {}

$t = new TypedArray(CustomClass::class);

$t[] = new CustomClass(); // this is the right type
$t[] = new InheritedClass(); // it inherit, so it is still a good value
$t[] = new stdClass(); // the parent class could not work, WrongValueException is thrown

很好,但如何让它按你的方式工作呢?

<?php
use TypedArray\TypedArray;

$t = new TypedArray(function ($_item, $_key, $_this): bool {
    return is_int($_item) && $_item >= 0; // check for positive integer
});

$t[] = 4; // a positive integer
$t[] = 0; // null but still accepted
$t[] = -1; // below 0, so the WrongValueException is thrown

如果你改变了主意,你可以设置一个新的类型或一个新的检查器,就像之前显示的那样。不需要传递值给构造函数,只需使用 setCheckMethod() 方法即可。

<?php
use TypedArray\TypedArray;

$t = new TypedArray(TypedArray::TYPE_INT);
$t[] = 1;
$t[] = 2;

// now we are allowing larger set of entries
$t->setCheckMethod(TypedArray::TYPE_NUMERIC);
$t[] = 2.5;