物件導向程式設計由三種主要的機制構成:封裝、繼承與多型
所謂封裝,就是把程式包成class,隱藏內部實現細節(private的property、method),提供外部訪問方式。
這樣講可能有點抽象,可以參考下面這個範例比較容易理解:
<?php
class Car{
public $color;
public $size;
private $runningSpeed;
function __construct($color, $size, $speed)
{
$this->color = $color;
$this->size = $size;
$this->runningSpeed = $speed + 50;
}
private function speedUp($runningSpeed){
$speed = $runningSpeed + 50;
return $speed;
}
public function run(){
$finalSpeed = $this->speedUp($this->runningSpeed);
echo "The car run in $finalSpeed km/hr.\n";
}
}
$myCar = new Car('black', 5, 10);
$myCar->run();
在class以外的地方,只能使用到run()這個method,$initialSpeed、speedUp()這些都被封裝在class中,也就是說,外部可視的部份只有run()這個介面,至於車的初始速度、如何加速等,只有在class內部可見,外部是不可見的,這就是所謂的"封裝"。
子類別和父類別在繼承的關係下,擁有相似的特徵,包括properties和methods,
如此一來能讓程式碼得以重複使用,而不必複製父類別的程式碼到其所衍生出的子類別中。
每個子類別都繼承了父類別的特徵,並加入自己特殊的特徵,這個就是所謂的extension。
我們可以說,子類別是一種父類別,
例如:HourlyEmployee is an Employee、SalariedEmployee is an Employee
範例:
//父類別
class Employee{
protected $name;
protected $hireDate;
public function getHireDate($date){
$this->hireDate = $date;
echo "Hire date is $this->hireDate.\n";
}
public function getName($name){
$this->name = $name;
echo "Employee's name is $this->name.\n";
}
protected function speak(){ //子類別可調用此method
echo "I'm an employee of this company\n";
}
}
//子類別
class HourlyEmployee extends Employee
{
public function speak(){
echo "I'm an hourly employee of this company\n";
}
}
$hourlyEmployee = new HourlyEmployee;
$hourlyEmployee->getName('Jenny');
//output:Employee's name is Jenny.
$hourlyEmployee->getHireDate('10/23');
//output:Hire date is 10/23.
$hourlyEmployee->speak();
//output:I'm an hourly employee of this company