<!-- 学习类以前,先掌握几个函数: 一、 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; */ ?>