封裝將資料與操作包裝在類別內部,透過存取修飾符控制可見性,保護資料完整性。
| 修飾符 | 類別外部 | 繼承類別 | 本類別 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✗ | ✓ | ✓ |
| private | ✗ | ✗ | ✓ |
public。$this->方法名()。<?php
class Person {
public $name; protected $age; private $salary;
function __construct($name,$age,$salary){
$this->name=$name; $this->age=$age; $this->salary=$salary;
}
function showInfo(){ echo $this->name."||".$this->age."||".$this->salary."<br/>"; }
// 提供公用方法存取私有屬性
function getSalary($user,$pass){
if($user=="www.bianceng.cn" && $pass==123) return $this->salary;
else echo "無權限查看薪資";
}
public function setAge($age){
if($age>=1 && $age<=120) $this->age=$age;
else echo "年齡範圍錯誤";
}
public function getAge(){ return $this->age; }
}
$p1=new Person("張三",30,1000);
echo $p1->name; // 可存取
$p1->showInfo(); // 內部可存取所有
echo $p1->getSalary("www.bianceng.cn",123); // 經驗證存取
$p1->setAge(75); echo $p1->getAge(); // 受控修改與讀取
?>
__set / __get(不建議使用)可攔截對不可見屬性的讀寫,但現代開發建議改用明確的 getter/setter 方法,提高程式碼可讀性與維護性。