5ol.cc 发表于 2017-12-30 07:40:00

PHP中interface与 implements 关键字

<?php  

//简单定义实现接口  
interface UserInterface{//定义user接口
  
    function getname();
  
}
  
interface TeacherInterface{    //定义teacher接口
  
    function getLengthofService();
  
}
  
class User implements UserInterface{ //实现user接口
  private $name="nostop";
  public function getName(){
  return $this->name;
  }
  
}
  
class Teacher implements TeacherInterface{ //实现teacher接口
  private $age=23;
  public function getLengthofService(){
  return $this->age;
  }
  
}
  
$user=new User();
  
echo $user->getName().'<br />';//nostop
  
$teacher=new Teacher();
  
echo $teacher->getLengthofService().'<br />';//23
  
//继承类实现接口
  
class GraduResultudent extends User implements TeacherInterface{ //继承User类 实现接口
  private $teacher;
  public function __construct(){   //定义构造函数
  $this->teacher=new Teacher();//实例化Teacher对象
  
    }
  public function getLengthOfService(){ //实现TeacherInterface接口的方法
  return $this->teacher->getLengthOfService();
  }
  
}
  

  
class Result{
  public static function getUserName(UserInterface $_user){ //注意:这里面的类型变成接口类型
  echo "Name is ".$_user->getName().'<br />';
  }
  public static function getLengthOfService(TeacherInterface $_teacher){ //注意:这里面的类型变成接口类型
  echo "age is ".$_teacher->getLengthOfService();
  }
  
}
  

  
$object=new GraduResultudent();
  
Result::getUserName($object); //Name is nostop
  
Result::getLengthOfService($object); //age is 23
  
echo "<br />";
  
//接口实现用户的折扣
  
interface People{    //定义接口
  
    function getUserType();
  function getCount();
  
}
  

  
class VipUser implements People{ //实现接口
  //用户折卡系数
  private $discount=0.8;
  function getUserType(){
  return "VIP用户";
  }
  function getCount(){
  return    $this->discount;
  }
  
}
  

  
$vip=new VipUser();    //实现化对象
  
echo $vip->getUserType().'商品价格:'.$vip->getCount()*100;//VIP用户商品价格:80
  

  
class Goods{
  var $price=100;
  var $member;
  function run(People $member){ //注意:这里面的参数类型是接口类型
  $this->member=$member;
  $discount=$this->member->getCount();
  $usertype=$this->member->getUserType();
  echo $usertype."商品价格:".$this->price*$discount;
  }
  
}
  
$display=new Goods();
  
$display->run(new VipUser);//VIP用户商品价格:80
  

  
?>
页: [1]
查看完整版本: PHP中interface与 implements 关键字