这更多的是语义问题,而不是每个说的最佳实践。
在您的示例中,您的业务逻辑可能会确定动物始终需要名称。所以用名字来构造对象是有意义的。如果您不想允许更改动物的名称,则不要编写 setter。
IE
class Animal
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
您可能具有动物不需要的其他属性,例如您只为它编写 getter/setter 的所有者
class Animal
{
private $name;
private $owner;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setOwner($owner)
{
$this->owner = $owner
}
}
但是如果你发现你总是在同时创建一个动物和一个主人,你可能想把它放在承包商签名中以方便起见
class Animal
{
private $name;
private $owner;
public function __construct($name, $owner = null)
{
$this->name = $name;
$this->owner = $owner;
}
public function getName()
{
return $this->name;
}
public function setOwner(Owner $owner)
{
$this->owner = $owner
}
public function getOwner()
{
return $this->owner;
}
}
如果所有者是您的应用程序中的另一个类,您可以键入提示您的构造函数需要特定类型(类)的所有者。所有这些都是为了让您或其他开发人员更容易理解代码背后的一些要求/逻辑 - 以及可能在这里或那里发现错误
class Owner
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
}
class Animal
{
private $name;
private $owner;
public function __construct($name, Owner $owner = null)
{
$this->name = $name;
$this->owner = $owner;
}
public function getName()
{
return $this->name;
}
public function setOwner(Owner $owner)
{
$this->owner = $owner
}
public function getOwner()
{
return $this->owner;
}
}
// Create a new owner!
$dave = new Owner('Farmer Dave');
// a standard php empty object
$otherObj = new \stdClass();
// Create a new animal
$daisy = new Animal('Daisy');
// Farmer dave owns Daisy
$daisy->setOwner($dave);
// Throws an error, because this isn't an instance of Owner
$daisy->setOwner($otherObj);
// Set up Maude, with Dave as the owner, a bit less code than before!
$maude = new Animal('Maude', $dave);