PHP继承构造函数不起作用

时间:2018-05-04 12:40:53

标签: php oop

请检查我的问题我制作一个脚本,但$contractempsal变量不起作用。我想要员工薪水,但我得到了错误。请检查。

关注我的代码: -

<?php
class baseemp {

protected $firstname;
protected $lastname;

public function getfullname() {

return $this->firstname .''. $this->lastname; 

}   

 public function __construct($first,$last) {

$this->firstname="$first";
$this->lastname="$last";
}   

}

 class fulltimeemp extends baseemp {

public $monthlysal;

 public function monthlysalary() {

$this->monthlysal/12;

}   
}

  class contractemp extends baseemp {


public $hourlyrate;
public $totalhours;

  public function monthlysalaryy() {


$this->hourlyrate * $this->totalhours;
  }
   public function __construct($hourrate,$totalhoursd){

$this->hourlyrate="$hourrate";
$this->totalhours="$totalhoursd";

}   
  }

   $fulltimeemployee = new fulltimeemp("kannu"," singh");
    $contractempsal = new contractemp("400","5");

   echo $fulltimeemployee->getfullname();

   echo $contractempsal->getfullname();

    ?>

所以,这是我的代码。请检查并告诉我我错在哪里谢谢

请检查我的问题我制作一个脚本,但$contractempsal变量不起作用。我想要员工薪水,但我得到了错误。请检查。

1 个答案:

答案 0 :(得分:-1)

您需要更新constractemp类的__construct函数,然后调用parent::__construct来设置名字和姓氏。

<?php
class baseemp {

    protected $firstname;
    protected $lastname;

    public function getfullname() {
        return $this->firstname .''. $this->lastname; 
    }   

    public function __construct($first,$last) {
        $this->firstname="$first";
        $this->lastname="$last";
    }   
}

class fulltimeemp extends baseemp {

    public $monthlysal;

    public function monthlysalary() {
        $this->monthlysal/12;
    }   
}

class contractemp extends baseemp {

    public $hourlyrate;
    public $totalhours;

    public function monthlysalary() {
        return $this->hourlyrate * $this->totalhours;
    }
    public function __construct($first,$last, $hourrate, $totalhoursd){
        parent::__construct($first,$last);
        $this->hourlyrate="$hourrate";
        $this->totalhours="$totalhoursd";
    }   
}

$fulltimeemployee = new fulltimeemp("kannu"," singh");
$contractempsal = new contractemp("kannu"," singh", "400","5");

echo $fulltimeemployee->getfullname(); // display kannu singh

echo $contractempsal->getfullname(); // display kannu singh

echo $contractempsal->monthlysalary(); // display 2000