ajf / newtype
一个用于创建不可透明类型的便捷函数
v1.0.3
2018-01-24 19:55 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- phpunit/phpunit: ^5.0
This package is not auto-updated.
Last update: 2024-09-14 18:20:34 UTC
README
newType()
是一个用于创建不可透明类型的便捷函数,也就是说,只是包装另一个类型的类型。它接受两个参数:你新包装类型的名称,以及你想要包装的类型名称。你将得到一个带有接受包装类型值的构造函数的类,以及一个 ->unbox()
方法来获取包装类型的值。
使用 composer require ajf/newtype
命令安装以使用它。它仅适用于 PHP 7,因为 PHP 7 是第一个支持标量类型声明的 PHP 版本。尽管如此,仍然可以实现回滚。
你可能使用此功能的一个示例
<?php namespace JaneBlogges\WonderfulApp; use function ajf\newType\newType; // Makes the new opaque type! newType(FilePath::class, 'string'); function moveFile(FilePath $sourcePath, FilePath $destinationPath): bool { return rename($sourcePath->unbox(), $destinationPath->unbox()); } moveFile(new FilePath('foo'), new FilePath('bar'));
使用它以获得额外的类型安全性!
如果你需要一个不需要显式转换的简单别名,请查看 PHP 的内置 class_alias
函数 - 但请注意,它仅适用于类,而不是原始类型。
名称来源于 Haskell 的 newtype
声明,它执行相同的功能
newtype FilePath = FilePath String
它还类似于 Hack 的 newtype
声明,尽管它的工作方式略有不同。