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包含多種類型的實例
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報