php - 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();
解决方案
你定义$salary
为private
这意味着继承类将无权访问它。如果Employee
应该访问它,您需要定义$salary
为protected
或使用getSalary()
推荐阅读
- jsf - JSF2.3 的外部资源处理程序
- python - Python 将 JSON 写入 S3
- r - 多行相同的行,但行的数量不同
- python - 如何从 UTF16-BE 编码数据中获取双精度值?
- php - Magento 正在重定向到 xampp 仪表板页面
- postman - 如何在 Postman 中从 URL 上传文件作为 multipart/form-data
- vim - 寻找插件/方式如何在 Vim 的 `.md` 文件中突出显示语法
- python - ModuleNotFoundError:没有名为“pycge.PyCGE”的模块
- python - 等到文件复制/上传完成
- wordpress - 单字符邮政编码的 WooCommerce 统一费率