【问题标题】:PHP inheritance constructor function didn't workPHP继承构造函数不起作用
【发布时间】:2018-05-04 12:40:52
【问题描述】:

请检查我的问题,我制作了一个脚本,但 $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 变量不起作用。我想要员工工资,但我出错了。请检查。

【问题讨论】:

  • “我出错了”什么错误?你已经做了哪些调试?
  • 对不起,我没有收到错误,它显示空白屏幕
  • 我只是想得到员工的薪水,但它什么也没显示:(
  • 检查您的错误日志和/或启用错误报告。
  • 你从我的代码中认为这合适吗??

标签: php oop


【解决方案1】:

您需要更新 constructemp 类的 __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

【讨论】:

  • 对不起,您的代码无法正常工作,它再次显示空白,结果中没有显示员工工资:(
  • 我刚更新,大家看看。所以现在,两个函数都显示“kannu singh”。是你想要的吗?
  • 只是检查请稍候
  • 警告:contractemp::setEmployeeFullname() 缺少参数 1,在第 240 行的 D:\xampp\htdocs\oops\index.php 中调用并在 D:\xampp\htdocs\oops\ 中定义第 217 行的 index.php 注意:未定义的变量:第 218 行的 D:\xampp\htdocs\oops\index.php 中的employeeFullName
  • 请您在我的 php 代码中更新您的代码,然后我会全面检查
猜你喜欢
  • 2014-10-19
  • 2013-03-05
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 2013-06-01
相关资源
最近更新 更多