Oop 避免PHP7.4中的getter和setter
由于PHP 7.4支持类型化类属性:。看起来很多代码都可以删除,特别是负责控制属性类型的实体和DTO中的getter和setter。例如,这样的代码片段:Oop 避免PHP7.4中的getter和setter,oop,php-7.4,Oop,Php 7.4,由于PHP 7.4支持类型化类属性:。看起来很多代码都可以删除,特别是负责控制属性类型的实体和DTO中的getter和setter。例如,这样的代码片段: class Foo implements BarInterface { /** * @var int */ protected $id; /** * @var int|null */ protected $type; /** * @return in
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;
}
这是个好主意,对吗?在进行此类重构时,我应该考虑什么?不,创建类的属性不是一个好主意public@Jens一些争论为什么?虽然我在文章中找到了作者建议做的相同的事情,我想做的相同的事情,但是对于物体的嵌入的论点是清楚的,对于DTO来说,对任何公共事物的考虑都是假设在某个时刻会有一些非预期的东西与之交互,并且很有可能很难识别系统所获得的复杂度。简单系统可能不需要此设计最佳实践。