1、类和对象
类的基本声明格式:
class 类名{
//类体
}
用class实现类的定义,例如:
class point
{
var $x;//点的x坐标
var $y;//点的y坐标
function setx($px=0) //设置x坐标值
{
$this->x=$px;
}
function sety($py=0) //设置y坐标值
{
$this->y=$py;
}
function getx() //得到x坐标值
{
return $this->x;
}
function gety() //得到y坐标值
{
return $this->y;
}
}
用new实现对象的创建,方法:"$对象名=new 类名"
$mypoint=new point;
$mypoint->setx(10);//引用类中的方法可以使用"->"
$mypoint->sety(10);
还可以通过赋值操作来赋值对象
$newpoint=$mypoint;
2、类的使用与实例化
class point
{
var $x;//点的x坐标
var $y;//点的y坐标
function point()
{
$this->x=0;
$this->y=0;
}
function setx($px=0)
{
$this->x=$px;
}
function sety($py=0)
{
$this->y=$py;
}
function getx()
{
return $this->x;
}
function gety()
{
return $this->y;
}
}
$mypoint=new point;
$var1=$mypoint->getx();
$var2=$mypoint->gety();
echo"$var1,$var2<br>";
$mypoint->setx(10);
$mypoint->sety(10);
$var1=$mypoint->getx();
$var2=$mypoint->gety();
echo"$var1,$var2<br>";
构造函数也可以接受参数,可以在对象实例化时指定初始化的值,例如:
class point
{
var $x;
var $y;
function point($x=0,$y=0)
{
$this->x=$x;
$this->y=$y;
}
function getx()
{
return $this->x;
}
function gety()
{
return $this->y;
}
}
$mypoint=new point(10,10);
$var1=$mypoint->getx();
$var2=$mypoint->gety();
echo "$var1,$var2<br>";
3、类的继承与多态
用extends实现类的继承。方法:class 父类名 extends 子类名//
class point
{
var $x;
var $y;
function point($x=0,$y=0)
{
$this->x=$x;
$this->y=$y;
}
function setx($px=0)
{
$this->x=$px;
}
function sety($py=0)
{
$this->y=$py;
}
function getx()
{
return $this->x;
}
function gety()
{
return $this->y;
}
function moveto($x,$y)
{
if($x<0||$y<0)
{
echo"move failed!<br>";
return;
}
$this->x=$x;
$this->y=$y;
echo"move success!<br>";
}
}
class circle extends point
{
var $radius;
function circle($x=10,$y=10,$r=5)
{
$this->x=$x;
$this->y=$y;
$this->radius=$r;
}
function setradius($r)
{
$this->radius=$r;
}
function getradius($r)
{
return $this->radius;
}
function moveto($x,$y)
{
if($x<($this->radius)||$y<($this->radius))
{
echo"move failed!<br>";
return;
}
$this->x=$x;
$this->y=$y;
echo"move success!<br>";
}
}
$mypoint=new point(20,20);
$mycircle=new circle(20,20,10);
$mycircle->setx(30);
$mypoint->moveto(5,5);
$mycircle->moveto(5,5);