将PHP类型作为对象处理

1.0.0 2024-01-11 06:48 UTC

This package is auto-updated.

Last update: 2024-09-11 08:22:46 UTC


README

tests version downloads license

此包提供将类型作为对象工作的能力。

可用类型

  • 整数
  • 字符串
  • 浮点数
  • 布尔值
  • 数组

安装

composer require elegant-php/types

使用方法

使用预定义的类和协议

final class AuthorizedUser implements User
{
  public function __construct(
    private readonly StringType $name
  ) { }
}

$user = new AuthorizedUser(new DefaultString('my user'));

实现类型协议

final class UserName extends StringType
{
  public function __construct(
    private readonly string $name
  ) { }

  public function value(): string
  {
    return strtolower($this->name);
  }
}

比较类型

$first = new DefaultString('first');
$second = new DefaultString('first');

var_dump($first->equals($second));

// bool(false)

类型转换

$id = new StringAsInteger('123');

var_dump($id->value());

// int(123)

发布说明