paragonie/typed-arrays

为 PHP 8.3 及更高版本提供的严格类型标量数组

dev-main 2024-05-14 21:24 UTC

This package is auto-updated.

Last update: 2024-09-14 22:11:19 UTC


README

Build Status Latest Stable Version Latest Unstable Version License Downloads

需要 PHP 8.3。这最好通过示例来描述

<?php
require_once 'vendor/autoload.php';

class Foo
{
    public function __construct(
        public readonly string⟦⟧ $foo,
        public readonly int⟦⟧ $bar
    ) {}
}

$x = new Foo(
    string⟦⟧('apple', 'bee'),
    int⟦⟧(4, 5, 120000),
);
var_dump($x->foo, $x->bar);
var_dump($x->foo[1]);

这将输出以下内容

object(string⟦⟧)#5 (2) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(3) "bee"
}
object(int⟦⟧)#6 (3) {
  [0]=>
  int(4)
  [1]=>
  int(5)
  [2]=>
  int(120000)
}
string(3) "bee"

如果你尝试传递一个错误类型,你会得到一个 TypeError

<?php
declare(strict_types=1);
require_once 'vendor/autoload.php';

class Foo
{
    public function __construct(
        public readonly string⟦⟧ $foo
    ) {}
}

$x = new Foo(
    string⟦⟧('apple', 'bee', 25)
);
var_dump($x->foo, $x->bar);

应产生

Fatal error: Uncaught TypeError: string⟦⟧(): Argument #3 must be of type string, int given

这个包是做什么的?

我们使用 Unicode 字符()来创建一个实现了 ArrayAccess 的类。然后所有这些类型的参数都是严格类型的。

实际上,我们将一个类转换成了一个你的 IDE 不会抱怨的严格类型数组。

它支持多级类型吗?例如 string⟦⟧⟧

当然。

<?php
declare(strict_types=1);
require_once 'vendor/autoload.php';

class Bar
{
    public function __construct(
        public readonly string⟦⟧⟦⟧ $double,
    ) {}
}

$test = new Bar(string⟦⟧⟦⟧(
    string⟦⟧('test'),
    string⟦⟧('example'),
));
var_dump($test->double);

这将产生

object(string⟦⟧⟦⟧)#7 (2) {
  [0]=>
  object(string⟦⟧)#5 (1) {
    [0]=>
    string(4) "test"
  }
  [1]=>
  object(string⟦⟧)#6 (1) {
    [0]=>
    string(7) "example"
  }
}

这支持类数组吗?

当然!

<?php
declare(strict_types=1);
require_once 'vendor/autoload.php';

class Foo {}

class Bar
{
    public function __construct(
        public readonly Foo⟦⟧ $example
    ) {}
}

$test = new Bar(new Foo⟦⟧(new Foo));
var_dump($test);

输出

object(Bar)#2 (1) {
  ["example"]=>
  object(Foo⟦⟧)#5 (1) {
    [0]=>
    object(Foo)#6 (0) {
    }
  }
}

它是如何为我的类创建类型的?

请参阅: 自动加载器