1、定义
要有构造方法__construct()(下划线有两个),类成员,类方法。其中关键字有public(可以直接调用此类数据成员),private(需要为每个成员编写get或set()函数),protected,默认public。例:
<?php
class point{
private $x;
private $y;
function __construct($x,$y){
$this->x=$x;
$this->y=$y;
}
function get_x(){
return($this->x);
}
function get_y(){
return($this->y);
}
function dist($p){
return(sqrt(pow($this->x-$p->get_x(),2)+pow($this->y-$p->get_y(),2)));
}
}
$p1=new point(2,3);
$p2=new point(3,4);
echo $p1->dist($p2),"\n";
?>
2、继承和重载
在PHP中一个类只有一个单亲父亲,PHP不支持多重继承。父类函数可以通过parent::结构在子类中调用。
<?php
class employee{
protected $name;
protected $sal;
function __construct($name,$sal=500){
$this->name=$name;
$this->sal=$sal;
}
function giveRaise($amount){
$this->sal+=$amount;
echo "Employee ".$this ->name." got a raise of ".$amount." dollars.","\n";
echo "New sal is ".$this->sal." dollars.","\n";
}
function __destruct(){}
}
class manager extends employee{
protected $dept;
function __construct($name,$sal,$dept){
parent::__construct($name,$sal);
$this->dept=$dept;
}
function giveRaise($amount){
parent::giveRaise($amount);
echo "This employee is a manager.","\n";
}
function __destruct(){}
}
$mar=new manager("Smith",400,20);
$mar->giveRaise(50);
$emp=new employee("John",300);
$emp->giveRaise(50);
?>
在上述实例中,manager类中的giveRaise()函数重载了employee类中的函数。如果函数标记为final,就不可以被重载。如finalfunction giveRaise(){…}
关于抽象类,抽象类不能够实例化,主要用作模板,,使继承他们的类具有期望的结构。关键字abstract。如abstractclass A{…}。当然,也可以申明抽象类的抽象方法。
还有接口、迭代器等,在以后的学习中再写。