improved/类型

v0.1.1 2019-02-20 21:41 UTC

This package is auto-updated.

Last update: 2024-09-12 04:59:13 UTC


README

improved PHP library

类型处理

PHP Scrutinizer Code Quality Code Coverage Packagist Stable Version Packagist License

用于类型处理的库。

此库为PHP提供了一套一致的功能。您应始终使用这些类型,而不是PHP原生提供的类型。

安装

composer require improved/type

类型

参考

type_is

bool type_is(mixed $var, string|string[] $type)

如果变量具有指定的类型,则返回true。

作为类型,您可以指定任何内部类型,包括callableobject,类名或资源类型(例如stream resource)。

不支持类型数组或迭代器,因为这需要遍历它们。

可以在类中添加一个问号以接受null,例如"?string"类似于使用["string", "null"]

type_check

mixed type_check(mixed $var, string|string[] $type, Throwable $throwable = null)

验证变量是否具有特定类型。与type_is()中相同类型的类型可以用于此。

不支持类型数组或迭代器。请改用iterable_check_type

默认情况下会抛出TypeError。您可以传递一个异常作为替代。

消息可能包含一个%s,它将被替换为$var的类型描述。它还可能包含一个可选的第二个%s,它将被替换为所需类型的描述。使用sprintf定位来首先使用所需类型。

如果消息、异常或错误中包含一个%,将创建一个具有填充消息的同类型可抛出对象。

如果类型匹配,函数返回$var,因此您可以在设置变量时使用它。

use Improved as i;

$date = i\type_check(get_some_date(), DateTimeInterface::class);
$name = i\type_check($user->getName(), 'string');
$number = i\type_check(get_distance(), ['int', 'float']);

$foo = i\type_check(do_something(), Foo::class, new UnexpectedException('Wanted %2$s, not %1$s'));

可以在类中添加一个问号以接受null,例如"?string"类似于使用["string", "null"]

type_cast

mixed type_cast(mixed $var, string $type, Throwable $throwable = null)

检查变量是否具有特定类型或可以转换为此类型,否则抛出TypeError或异常。

此函数类似于type_check,但不同之处在于它在某些情况下会转换值。

type_istype_check不同,只能指定一个类型。

可以在类中添加一个问号以接受null,例如?string将尝试将所有内容转换为字符串,除了null

type_describe

string type_describe(mixed $var, bool $detailed = false)

以描述性方式获取变量的类型,用于在(错误)消息中。

对于标量、null和数组值,结果与gettype相同。对于浮点数,将返回float而不是double

对象具有其类名,后跟object。对于资源,返回资源类型,后跟resource

type_describe('hello');        // string
type_describe(22);             // integer
type_describe(STDIN);          // stream resource
type_describe(new DateTime()); // instance of DateTime

详细选项描述了值和类型。这与type_checktype_cast的错误消息中使用的类似。

type_describe('hello');         // string(5) "hello"
type_describe(22);              // int(22)
type_describe(["a", "b", "c"]); // array(3)