继承这个类,你可以重写默认信息。
你可以延迟加载对象的属性,比如从服务器获取数据。
此外,这样的方式也符合 OOP 开发中的 [开闭原则](# 开闭原则 (OCP))
不好的:
class BankAccount
{
public $balance = 1000;
}
$bankAccount = new BankAccount();
// Buy shoes...
$bankAccount->balance -= 100;
好的:
class BankAccount
{
private $balance;
public function __construct(int $balance = 1000)
{
$this->balance = $balance;
}
public function withdraw(int $amount): void
{
if ($amount > $this->balance) {
throw new \Exception('Amount greater than available balance.');
}
$this->balance -= $amount;
}
public function deposit(int $amount): void
{
$this->balance += $amount;
}
public function getBalance(): int
{
return $this->balance;
}
}
$bankAccount = new BankAccount();
// Buy shoes...
$bankAccount->withdraw($shoesPrice);
// Get balance
$balance = $bankAccount->getBalance();
让对象拥有 private/protected 属性的成员
- public 公有方法和属性对于变化来说是最危险的,因为一些外部的代码可能会轻易的依赖他们,但是你没法控制那些依赖他们的代码。 类的变化对于类的所有使用者来说都是危险的。
- protected 受保护的属性变化和 public 公有的同样危险,因为他们在子类范围内是可用的。也就是说 public 和 protected 之间的区别仅仅在于访问机制,只有封装才能保证属性是一致的。任何在类内的变化对于所有继承子类来说都是危险的 。
- private 私有属性的变化可以保证代码 只对单个类范围内的危险 (对于修改你是安全的,并且你不会有其他类似堆积木的影响 Jenga effect).
因此,请默认使用 private 属性,只有当需要对外部类提供访问属性的时候才采用 public/protected 属性。
更多的信息可以参考Fabien Potencier 写的针对这个专栏的文章blog post .
Bad:
class Employee
{
public $name;
public function __construct(string $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(string $name)
{
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
}
$employee = new Employee('John Doe');
echo 'Employee name: '.$employee->getName(); // Employee name: John Doe
类
组合优于继承
