亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 PHP 7.4 中獲取類型化屬性的類型

在 PHP 7.4 中獲取類型化屬性的類型

PHP
繁花不似錦 2022-06-11 09:32:19
我有一個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;}我正在嘗試制作某種自動映射器來填充屬性,但是我需要檢查變量的類型,但這似乎是不可能的。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;        }    }}ContactInputDto:class ContactInputDto extends BaseDto{    public string $firstname;    public string $lastname;    public string $street_housenumber;    public string $postal_code;    public string $place;    public string $country;    public string $email;    public string $phone;}是否有可能使該行"gettype($this->$key)"工作,而不會引發以下錯誤:類型化屬性 App\Dto\CreateMembershipInputDto::$is_gift 在初始化之前不得訪問
查看完整描述

1 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

雖然該手冊目前似乎沒有記錄它,但添加了一種方法ReflectionProperty來允許您獲取類型。這實際上是在RFC 中為類型化屬性指定的


以下是您將如何使用它:


class CreateMembershipInputDto extends BaseDto {

    public bool $is_gift;

    public int $year;

    public string $name;

    public \DateTime $shipping_date;

    public ContactInputDto $buyer;

    public ?ContactInputDto $receiver;

}


class BaseDto

{

    public function __construct($json)

    {   

        $r = new \ReflectionClass(static::class); //Static should resolve the the actual class being constructed

        $jsonArray = json_decode($json, true);

        foreach($jsonArray as $key=>$value){

            $prop = $r->getProperty($key);

            if (!$prop || !$prop->getType()) { continue; } // Not a valid property or property has no type   

            $type = $prop->getType();

            if($type->getName() === BaseDto::class) //types names are strings

                $this->$key = new $type($value);

            else

                $this->$key = $value;

        }

    }

}


如果您想檢查類型是否擴展BaseDto,您將需要(new \ReflectionClass($type->getName()))->isSubclassOf(BaseDto::class)


注意getName指的是ReflectionNamedType::getName。在 PHP 8 之前,這是您可以獲得的唯一可能的實例,$prop->getType()但是從 PHP 8 開始,您可能還會獲得一個ReflectionUnionType包含多種類型的實例


查看完整回答
反對 回復 2022-06-11
  • 1 回答
  • 0 關注
  • 171 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號