在 PHP 中,经过为属性或方法设置 public, protected 和 private 关键字能够实现对属性或方法的可见性控制。不过,经过 getter 和 setter 也能够达到控制可见性的目的,而且在某些场景下它具有一些额外的好处。php
使用 getter和 setter 有如下好处:函数
另外,这是面向对象的基本设计原则中的开放/封闭原则。this
Bad:设计
class BankAccount { public $balance = 1000; } $bankAccount = new BankAccount(); // 买了一双鞋... $bankAccount->balance -= 100;
Good:日志
class BankAccount { private $balance; public function __construct($balance = 1000) { $this->balance = $balance; } //作一些事情 public function withdrawBalance($amount) { if ($amount > $this->balance) { throw new \Exception('Amount greater than available balance.'); } $this->balance -= $amount; } public function depositBalance($amount) { $this->balance += $amount; } public function getBalance() { return $this->balance; } } $bankAccount = new BankAccount(); // 买了一双鞋... $bankAccount->withdrawBalance($shoesPrice); // 获取结余 $balance = $bankAccount->getBalance();
Bad:code
class Employee { public $name; public function __construct($name) { $this->name = $name; } } $employee = new Employee('John Doe'); echo 'Employee name: '.$employee->name; // Employee name: John Doe
Good:对象
class Employee { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } $employee = new Employee('John Doe'); echo 'Employee name: '.$employee->getName(); // Employee name: John Doe
这里不是说不使用继承,使用“组合模式”和使用“继承”都有不少好的理由。继承
这里想说的是当你本能的要使用继承时就想想“组合模式”是否能更好帮你的解决问题。get
那么,你可能想知道,“何时应该用继承?”, 这取决于你手头上问题。it
如下几点说明了何时使用继承会更合适。
Bad:
class Employee { private $name; private $email; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } // ... } // 由于雇员和税收不是对等关系而是包含的关系 // 因此这里应用组合比较合适 class EmployeeTaxData extends Employee { private $ssn; private $salary; public function __construct($name, $email, $ssn, $salary) { parent::__construct($name, $email); $this->ssn = $ssn; $this->salary = $salary; } // ... }
Good:
class EmployeeTaxData { private $ssn; private $salary; public function __construct($ssn, $salary) { $this->ssn = $ssn; $this->salary = $salary; } // ... } class Employee { private $name; private $email; private $taxData; public function __construct($name, $email) { $this->name = $name; $this->email = $email; } public function setTaxData($ssn, $salary) { $this->taxData = new EmployeeTaxData($ssn, $salary); } // ... }