PHP Setter / Getters和构造函数
发布时间:2020-12-13 22:40:35 所属栏目:PHP教程 来源:网络整理
导读:我一直在网上搜索这个,但我似乎找不到足够清楚的东西让我理解.我在 Java中看到过类似的“类似”问题. class animal{ private $name; // traditional setters and getters public function setName($name){ $this-name = $name; } public function getName(){
我一直在网上搜索这个,但我似乎找不到足够清楚的东西让我理解.我在
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"); >我应该通过setter和getter或通过构造函数声明和访问我的私有字段吗? 请注意……这是我第一次使用OOP进行Web开发和PHP,并且我试图通过编写一些代码让我的手“脏”来学习,以便我理解OOP中的某些事情.请保持简单.
这更像是语义问题,而不是每种说法的最佳实践.
在您的示例中,您的商务逻辑可能会确定动物总是需要一个名字. 即 class Animal { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } 您可能拥有动物不必拥有的其他属性,例如所有者 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); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |