小编Bla*_*Ops的帖子

在 PHP 7.4 中获取类型属性的类型

我有一个DTO带类型的 PHP 变量:

class CreateMembershipInputDto extends BaseDto
{
    public bool $is_gift;
    public int $year;
    public string $name;
    public \DateTime $shipping_date;
    public ContactInputDto $buyer;
    public ?ContactInputDto $receiver;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试制作某种自动映射器,它填充属性,但我需要检查变量的类型,但这似乎是不可能的。

class BaseDto
{
    public function __construct($json)
    {
        $jsonArray = json_decode($json, true);
        foreach($jsonArray as $key=>$value){
            $type = gettype($this->$key);
            if($type instanceof BaseDto)
                $this->$key = new $type($value);
            else
                $this->$key = $value;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ContactInputDto:

class ContactInputDto extends BaseDto
{
    public string $firstname;
    public string $lastname;
    public string $street_housenumber;
    public string $postal_code;
    public …
Run Code Online (Sandbox Code Playgroud)

php php-7.4

2
推荐指数
1
解决办法
1904
查看次数

标签 统计

php ×1

php-7.4 ×1