<?php class yourclass{ public $name; private $age; protected $weight; function __construct($name,$age,$weight){ $this->name = $name; $this->age = $age; $this->weight = $weight; } private function get($key){ return $this->$key; } } class hisclass extends yourclass{ function key($key){ //父類別中get方法為private, 子類中不可存取, 故重新定義一個相同功能的函數 return $this->$key; } } $obj = new yourclass('tom',22,'60kg'); echo $obj->name; //echo $obj->age; // 將會報錯 echo $obj->get('age'); // 可通過呼叫公共方法存取 $son = new hisclass('jim',23,'70kg'); echo $son->name; echo $son->key('weight'); echo $son->key('age'); // 存取不到$age ?>執行以上程式的輸出結果為:
tom 22 jim 70kg
extends
,在子類中可使用parent
存取父類別的方法。在子類中可重寫父類別的方法。<?php class yourclass{ public $name; private $age; protected $weight; function __construct($name,$age,$weight){ $this->name = $name; $this->age = $age; $this->weight = $weight; } function like(){ echo "I like money. "; } function age(){ echo $this->name . ' is ' . $this->age . 'years old'; } protected function get($key){ return $this->$key; } function set($key,$value){ $this->$key = $value; } } class hisclass extends yourclass{ function get($key){ //重寫父類別方法 echo $this->key; } function what(){ parent::like(); //子類中存取父類別方法 } function getAge(){ $this->age(); //呼叫從父類別繼承來的方法 } } $obj = new hisclass('tom',22,'60kg'); //使用繼承自父類別的__construct方法初始化範例 $obj->get('name'); $obj->what(); $obj->set('age',33); $obj->getAge(); ?>執行以上程式的輸出結果為:
I like money. tom is 33years old
<?php class animal{ function can(){ echo "this function weill be re-write in the children"; } } class cat extends animal{ function can(){ echo "I can climb"; } } class dog extends animal{ function can(){ echo "I can swim"; } } function test($obj){ $obj->can(); } test(new cat()); test(new dog()); ?>上述例子便體現了物件導向的多型性,可以改進程式碼將 animal 類定義為抽象類,或者使用介面都是可以的,這樣就無須在父類別的方法中定義無意義的函數體了。