工具標籤
物件和資料結構
物件與資料結構 Objects and Data Structures
# 1. 使用 getters 和 setters Use object encapsulation
1. 使用 getters 和 setters
在PHP中你可以對方法使用public, protected, private 來控制物件屬性的變更。
-
當你想要對物件屬性做取得以外的操作時,你不需要在程式碼中去尋找並修改每一個該屬性存取方法
-
當有
set對應的屬性方法時,容易增加參數的驗證 -
封裝內部的表示
-
使用
set和get時,易於增加日誌和錯誤控制 -
繼承目前類別時,可以複寫預設的方法功能
-
當物件屬性是從遠端伺服器取得時,
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
相關影片
熱AI工具
免費脫衣圖片
用於從照片中去除衣服的線上人工智慧工具。
人工智慧驅動的應用程序,用於創建逼真的裸體照片
人工智慧支援投資研究,做出更明智的決策
熱門文章
熱門話題
20516
7
13630
4
11966
4
8985
17
8505
7
熱門工具
好用且免費的程式碼編輯器
中文版,非常好用
強大的PHP整合開發環境
視覺化網頁開發工具
神級程式碼編輯軟體(SublimeText3)












![PHP實戰開發極速入門: PHP快速創建[小型商業論壇]](https://img.php.cn/upload/course/000/000/035/5d27fb58823dc974.jpg)
