首页 > 解决方案 > PHP - 子类没有从父类继承

问题描述

这是 PacktPub 的《开始 PHP》第 3 课中的活动。据我了解,它应该创建一个 Employee 类的实例 $markus 。Employee 类是 BaseEmployee 的子类,因此继承了 BaseEmployee 的所有内容。但是,如果我尝试使用方法 calculateMonthlyPay(),则会出现通知并且程序无法正确运行。我正在使用 PHP7+ 和 PHPStorm IDE。这是通知消息和代码:

通知消息:

注意:未定义的属性:C:\Users\ed.PhpStorm2019.2\config\scratches.\scratch_3.php 中的 Employee::$salary PHP 注意:未定义的属性:C:\Users\ 中的 Employee::$salary ed.PhpStorm2019.2\config\scratches\scratch_3.php 在第 40 行每月支付 is0 过程以退出代码 0 完成

编码:

<?php
class BaseEmployee {
  private $name;
  private $title;
  private $salary;

  function __construct($name, $title, $salary){
    $this->name = $name;
    $this->title = $title;
    $this->salary = $salary;
  }

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

  public function setTitle($title){
    $this->title = $title;
  }

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

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

  public function getTitle(){
    return $this->title;
  }

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

class Employee extends BaseEmployee{
  public function calculateMonthlyPay(){
    return $this->salary / 12;
  }
}

$markus = new Employee("Markus Gray", "CEO", 100000);
echo "Monthly Pay is" . $markus->calculateMonthlyPay();

标签: phpoop

解决方案


你定义$salaryprivate

这意味着继承类将无权访问它。如果Employee应该访问它,您需要定义$salaryprotected或使用getSalary()


推荐阅读