<!-- 學習類以前,先掌握幾個函數: 一、 func_get_arg(int $arg_num) 返回參數列表,傳回項目 返回類型:mixed; 說明:返回自定義函數列表的第$arg_num個參數,默認從0開始,若是$arg_num的值大於實際列表的值,返回false; 二、 func_get_args() 返回包含函數參數的數組。 說明:返回數組,數組的數目由參數列組成。 三、 func_num_args() 返回傳遞的函數數量。 四、 function_exists() 檢查函數是否存在。 --> <?php /* 演示繼承類 */ //建立一個基類 class A { function __construct( ) { } function myfun() { echo "Class A : 類 A "; } function __destruct() { } } /* 測試 $a=new A(); $a->myfun(); */ //繼承 類A 的 Class B extends A { function __construct() {} function myfun($str){ echo A::myfun()."Class B : 類 B ".$str."\n"; } function __destruct(){} } Class C extends B //不支持多重繼承 { function __construct() {} function myfun($str){ echo A::myfun()."\n"; //這樣表示繼承至 A (應爲父類B繼承了A) echo parent::myfun($str)."\n"; //這樣表示繼承至 B echo "Class C : 類 C\n"; } function __destruct(){} } /* 測試結果 $m=new C(); $m->myfun('hello'); */ /* 演示重載構造函數(變通的方法)*/ Class D { function d(){ $name="d".func_num_args(); $this->$name(); } function d1() { echo 'd1'; } function d2(){ echo 'd2'; } } /* 測試結果 $d=new D(1); //調用d1 $d=new D(1,2); //調用d2 */ /* 抽象類和接口 */ //先定義抽象類 abstract class E { function myfun(){} function myfun1(){} } //繼承抽象類 class F extends E { function myfun(){ echo "類 F 繼承抽象類: E\n"; } } //繼承抽象類 class G extends E { function myfun1(){ echo "類 G 繼承抽象類: E\n"; } } /* 測試 $E=new E(); //這樣就會出錯,抽象類不能被實例化。 $f = new F(); $f->myfun(); $g = new G(); $g->myfun1(); */ // 定義一個接口 interface ih{ public function myfun(); public function myfun1($a,$b); } class H implements ih { public function myfun() { echo "實現接口 ih 函數:myfun "; } public function myfun1($a,$b) { echo "實現接口 ih 函數:myfun 參數1:".$a." 參數2 ".$b; } } /* //如下就會提示錯誤: Class I contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ih::myfun) class I implements ih { public function myfun1($a,$b) { echo "實現接口 ih 函數:myfun 參數1:".$a." 參數2 ".$b; } }*/ /* 測試 $h=new H(); $h->myfun(); $h->myfun1(1,a); */ /* 定義一個枚舉enum類 */ class enum { private $__this = array(); function __construct() { //調用屬性構造器 $args = func_get_args(); $i = 0; do{ $this->__this[$args[$i]] = $i; } while(count($args) > ++$i); } //屬性構造器 public function __get($n){ return $this->__this[$n]; } }; /* 測試結果 $days = new enum( "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ); $today = $days->Thursday; echo "enum : ".$today; */ ?>