su-rin/type

检查类型。

0.1.4 2020-02-29 19:55 UTC

This package is auto-updated.

Last update: 2024-09-29 05:02:17 UTC


README

检查类型

0.1.4

* 可选

TypeArray

描述:检查数组中的元素类型

<?php
interface C{}
class B{}
class A extends B implements C{}
$arrC = new TypeArray(C::class);
$arrB = new TypeArray(B::class);
$arrA = new TypeArray(A::class);
$arrN = new TypeArray("string"); //string|integer|double|boolean here
//$arrE = new TypeArray("SomeThingNotExists"); //error!!! class not found.

//init array like this
$arrIA = new TypeArray(A::class,[new A(),new A()]; //ok
//$arrIAE = mew TypeArray(A::class,[new B(),123,"abc"]) //error!!! incompatible type.

$arrC[] = new A; //can assign like this case.

$arrB[] = new A; //ok
$arrA[] = new A; //ok

//$arrA[] = 123; //error!!! incompatible type.

//$arrA[] = new B; //error!!! incompatible type.
$arrB[] = new A; //ok

//$arrN[] = .12; //error!!! incompatible type.

$arrA->checkType(B::class); //ok
//$arrB->checkType(A::class); //error!!! incompatible type.

print 'ok';
IDE中的建议(这里以phpstorm为例)
<?php
class A implements JsonSerializable
{
    public function get():int
    {
        return 1;
    }

    public function jsonSerialize()
        {
            return 1;
        }
}

//if you write comment like this

/** @var A[]|TypeArray $arr */
$arrA = new TypeArray(A::class);
$arrA[] = new A();
$arrA[] = new A();

//method get will hint in IDE. (A)
$arrA[0]->get();

//method checkType too. (TypeArray)
$arr->checkType(A::class);

//json support
json_encode($arrA);  // [1, 1]