默认情况下将所有 getter 字段设置为空是否是正确的决定,例如
/**
* @return int|null
*/
public function getId(): ?int
{
return $this->id;
}
这样做的解释是您可以创建实体和调用方法
$entinty = new Entity();
$entity->getId();
这将是没有可为空标志的致命错误。但是为什么有人会做这样的事情或有其他副作用呢?
这是正确的事情还是开销?
这取决于。
您的示例中不会遇到致命错误,但这真的有意义吗?此时永远不会有可用的 ID,因此您真的不应该调用它。
这就是我决定这样做的方式: 是否必须设置?然后甚至将其设置为这样的默认值
public $withDefault = true;
public function getWithDefault(): bool { ... }
或在构造函数中强制实施值
public $enforced;
public function __construct(int $enforced) { $this->enforced = $enforced; }
public function getEnforced(): int { ... }
在这些情况下,getter 不会返回 null。
对于所有其他情况,您应该使其依赖于数据库字段,如果该字段可为空,则 getter 可以返回 null。如果它不可为空,则 getter 也不应返回 null。