物件和資料結構


物件與資料結構 Objects and Data Structures

# 1. 使用 getters 和 setters Use object encapsulation

2. 給物件使用私有或受保護的成員變數

1. 使用 getters 和 setters

在PHP中你可以對方法使用public, protected, private 來控制物件屬性的變更。

  1. 當你想要對物件屬性做取得以外的操作時,你不需要在程式碼中去尋找並修改每一個該屬性存取方法

  2. 當有set對應的屬性方法時,容易增加參數的驗證

  3. 封裝內部的表示

  4. 使用setget時,易於增加日誌和錯誤控制

  5. 繼承目前類別時,可以複寫預設的方法功能

  6. 當物件屬性是從遠端伺服器取得時,get*set*易於使用延遲載入

此外,這樣的方式也符合OOP開發中的開閉原則

壞:

 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();

2. 給物件使用私有或受保護的成員變數

  • 對public方法和屬性進行修改非常危險,因為外部程式碼容易依賴他,而你沒辦法控制。對之修改影響所有這個類別的使用者。 public methods and properties are most dangerous for changes, because some outside code may easily rely on them and you can't control some code relies on them. Modifications in class are dangerous for all users of class.

  • 對protected的修改跟對public修改差不多危險,因為他們對子類別可用,他倆的唯一區別就是可調用的位置不一樣,對之修改影響所有集成這個類別的地方。 protected modifier are as dangerous as public, because they are available in scope of any child class. This effectively means that difference between public and protected is only in access mechanism, but class class class thesoo class thesem. es .

  • 對private的修改保證了這部分代碼只會影響當前類private modifier guarantees that code is dangerous to modify only in boundaries of single class (you are safe for modifications and you won't have Jenga effect).

所以,當你需要控制類別裡的程式碼可以被存取時才用public/protected,其他時候都用private

可以讀這篇 部落格文章 ,Fabien Potencier寫的.

壞:

 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

好:

 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