Pao*_*lla 6 php architecture getter setter constructor
我一直在网上搜索这个,但我似乎找不到足够清楚的东西让我理解.我在Java中看到过类似的"类似"问题.
class animal{
private $name;
// traditional setters and getters
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
// animal constructors
function __construct(){
// some code here
}
// vs
function __construct($name){
$this->name = $name;
echo $this->name;
}
}
$dog = new animal();
$dog->setName("spot");
echo $dog->getName();
// vs
$dog = new animal("spot");
Run Code Online (Sandbox Code Playgroud)
请注意......这是我第一次使用OOP进行Web开发和PHP,并且我试图通过编写一些代码让我的手"脏"来学习,以便我理解OOP中的某些事情.请保持简单.
这更像是语义问题,而不是每种说法的最佳实践.
在您的示例中,您的商务逻辑可能会确定动物总是需要一个名字.因此,使用名称构造对象是有意义的.如果您不想允许更改动物的名字,那么您不会写一个二传手.
即
class Animal
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
Run Code Online (Sandbox Code Playgroud)
您可能拥有动物不必拥有的其他属性,例如您只为其编写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
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果你发现你总是在同时拥有一个拥有者的动物你可能想把它放在构造函数签名中以方便
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果所有者是应用程序中的另一个类,则可以键入提示,即构造函数需要特定类型(类)的所有者.所有这些都用于使您或其他开发人员更容易理解代码背后的一些要求/逻辑 - 以及可能在此处或那里捕获错误
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);
Run Code Online (Sandbox Code Playgroud)