php的类的继承与重写

/*定义员工类*/
class Employee
{
  var $id;
  var $name;
  var $birthday;
  var $salary;

  //构造函数 用于对象的实例化 没有返回值
  function Employee($id,$name,$birthday,$salary){
    $this->setId($id);
    $this->setName($name);
    $this->setBirthday($birthday);
    $this->setSalary($salary);
  }

  function setId($id){
   $this->id=$id;
  }

  function setName($name){
   $this->name=strtoupper($name);
  }

  function setBirthday($birthday){
     $this->birthday=$birthday;
  }

  function setSalary($salary){
   $this->salary=$salary;
  }

  function getId(){
   return $this->id;
  }

  function getName(){
   return $this->name;
  }

    function getBirthday(){
   return $this->birthday;
  }

  function getSalary(){
   return $this->salary;
  }


  function getEmployeeInfo(){
     $info="员工号:".$this->getId()."|";
  $info.="姓名:".$this->getName()."|";
  $info.="生日:".$this->getBirthday()."|";
  $info.="工资:".$this->getSalary()."<br>";
  return $info;
  }
}

//利用构造函数进行实例化
$employee=new Employee(2007125,"employee1","1981-1-24",2000);
//$employee=new Employee
//$employee->setId(2007125);
//$employee->setName("wangjiafeng");
//$employee->setBirthday("1981-1-24");
//$employee->setSalary("2000");

print_r($employee);
echo "/n";
echo $employee->getEmployeeInfo();
echo "/n";

/*定义项目经理类,继承Employee类*/
class ProjectManager extends Employee{
 var $project_name;               //负责项目名称
 var $sub_employes=array();      //职员的名单

 //构造函数
 function ProjectManager($id,$name,$birthday,$salary){
        parent::Employee($id, $name, $birthday, $salary);  //parent:: $this-> 这里一个效果
 }

 function setProjectName($pjname){
  $this->project_name=$pjname;
 }

 function getProjectName(){
  return $this->project_name;
 }

 function addEmployee(&$employee){
  $this->sub_employes[]=& $employee;
 }

 //重写父类的方法
 function getEmployeeInfo(){
  $info="项目名:<b>".$this->getProjectName()."</b><br>"; //方法没有参数必须加()
  $info.="员工号:".$this->getId()."|";
     $info.="姓名:".$this->getName()."|";
     $info.="生日:".$this->getBirthday()."|";
     $info.="工资:".$this->getSalary()."<br>";
  $info.="-------------------------------------------------------<br>";

  foreach($this->sub_employes as $user)
  {
                $info.=$user->getEmployeeInfo();
  }

  return $info;
 }
}

$manager=new ProjectManager(2007120,"manager","1981-1-24",8000);
$manager->setProjectName("网上商城购物系统-PHP");
$manager->addEmployee($employee);   //按值传递如果外面$employee发生改变,那么$manager的内部成员变量$sub_employes也发生变化
$employee->setSalary(3000);
print_r($manager);

$employee1=new Employee(2007126,"employee2","1981-3-24",2020);
$manager->addEmployee($employee1);
echo "/n";
echo $manager->getEmployeeInfo();
echo "/n"; 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值