我有一个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 string $place;
public string $country;
public string $email;
public string $phone;
}
Run Code Online (Sandbox Code Playgroud)
是否有可能使该行"gettype($this->$key)"正常工作,而 php 不会抛出以下错误:
类型属性 App\Dto\CreateMembershipInputDto::$is_gift 在初始化之前不能被访问
虽然手册目前似乎没有记录它,但添加了一种方法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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想检查类型是否扩展,BaseDto您将需要(new \ReflectionClass($type->getName()))->isSubclassOf(BaseDto::class)
请注意,getName指的是ReflectionNamedType::getName。在 PHP 8 之前,这是您可以获得的唯一可能的实例,$prop->getType()但是从 PHP 8 开始,您也可能会得到一个ReflectionUnionType包含多种类型的
| 归档时间: |
|
| 查看次数: |
1904 次 |
| 最近记录: |