面向對象程序設計(OOP)將程式拆解為獨立單元(物件),每個物件封裝資料(屬性)與行為(方法),透過訊息傳遞協作。核心目標:重用性、靈活性、擴展性。
class Person { ... }$p = new Person();從靜態(屬性)與動態(方法)兩面描述實體:
class Person {
// 靜態屬性
public $name, $sex, $age, $height, $weight;
// 動態方法
public function drive() { echo "開車
"; }
public function speakEnglish() { echo "說英語
"; }
public function useComputer() { echo "使用電腦
"; }
}
屬性用 var(舊式)或可見性關鍵字宣告;方法用 function 定義。建構時不給屬性預設值,由各物件個別設定。
class Rect {
public $width, $height;
function perimeter() { return 2 * ($this->width + $this->height); }
function area() { return $this->width * $this->height; }
}
$r1 = new Rect(); $r1->width=5; $r1->height=10;
echo "周長:" . $r1->perimeter() . " 面積:" . $r1->area();