关于PHP的类的学习1

1、定义

要有构造方法__construct()(下划线有两个),类成员,类方法。其中关键字有public(可以直接调用此类数据成员),private(需要为每个成员编写getset()函数),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{…}。当然,也可以申明抽象类的抽象方法。

还有接口、迭代器等,在以后的学习中再写。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值