由于PHP 7.4支持键入的类属性:https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.typed-properties。看起来可以消除很多代码,特别是实体和DTO中负责控制属性类型的getter和setter。例如以下代码段:
class Foo implements BarInterface
{
/**
* @var int
*/
protected $id;
/**
* @var int|null
*/
protected $type;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
* @return $this
*/
public function setId(int $id)
{
$this->id = $id;
return $this;
}
/**
* @return int|null
*/
public function getType(): ?int
{
return $this->type;
}
/**
* @param int|null $type
* @return $this
*/
public function setType(?int $type)
{
$this->type = $type;
return $this;
}
}
可以重构为:
class Foo implements BarInterface
{
public int $id;
public ?int $type;
}
我是对的,这是个好主意吗?进行此类重构时应该考虑什么?