| 修飾詞 | 類別內 | 子類別 | 外部 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✗ |
| private | ✓ | ✗ | ✗ |
<?php
class Person {
private $name = 'NoName';
private $age = 0;
// Getter
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
// Setter(含驗證邏輯)
public function setName($name) {
if (strlen($name) < 2) {
throw new InvalidArgumentException('名稱至少 2 字元');
}
$this->name = $name;
}
public function setAge($age) {
if ($age < 0 || $age > 150) {
throw new InvalidArgumentException('年齡範圍 0-150');
}
$this->age = $age;
}
}
$person = new Person();
$person->setName('Tom');
$person->setAge(25);
echo $person->getName(); // Tom
echo $person->getAge(); // 25
?>
封裝優勢: 控制存取邏輯、保護資料完整性、方便未來修改實作細節。
class Calculator {
public function add($a, $b = 0) { // 預設值
return $a + $b;
}
public function sum(...$numbers) { // 可變參數 PHP 5.6+
return array_sum($numbers);
}
}
$calc = new Calculator();
echo $calc->add(5); // 5
echo $calc->add(5, 3); // 8
echo $calc->sum(1,2,3,4); // 10
PHP 7.4+ 支援型別宣告:
class Product {
public string $name = '';
public float $price = 0.0;
public int $stock = 0;
public bool $active = true;
public array $tags = [];
public ?string $description = null; // 可為 null
}
支援的標量型別:int、float、string、bool;複合型別:array、object、callable、iterable;特殊:resource、mixed(PHP 8.0+)。
$person = new Person();
$person->name = 'Tom'; // 寫入 public 屬性
echo $person->name; // 讀取
// 方法內部存取自身屬性
class Person {
public $name;
public function introduce() {
echo "我是 {$this->name}";
}
}
class Math {
public static $pi = 3.14159;
public static function circleArea($r) {
return self::$pi * $r * $r;
}
}
echo Math::$pi; // 3.14159
echo Math::circleArea(5); // 78.53975
__construct():建構子__destruct():解構子__call()/__callStatic():攔截不存在的方法__get()/__set()/__isset()/__unset():屬性多載__toString():物件轉字串__clone():複製行為__sleep()/__wakeup():序列化控制$util = new class {
public function greet($name) {
return "Hello $name";
}
};
echo $util->greet('World');
interface Loggable {
public function log(string $msg);
}
abstract class BaseService {
abstract protected function connect();
public function execute() { /* 模板方法 */ }
}
class UserService extends BaseService implements Loggable {
protected function connect() { /* 實作 */ }
public function log(string $msg) { /* 實作 */ }
}
PHP 5 奠定現代物件導向基礎,PHP 7/8 持續強化型別系統與效能。善用封裝、繼承、多型與介面,配合嚴格型別宣告,能建構健壯、可維護的大型應用程式。