<?php
//根据不同工龄发不同工资的实例。把处理工龄和工资的业务分别写成一个独立的类
class Person
{
private $work_year = 0;//工龄
private $salary;//工资属性
private $payoff;//发工资类
public function __construct()
{
//通过工资和工龄对应关系来计算工资
$this->payoff = new Payoff();
}
/**
* @return int
* 工龄
*/
public function getWorkYear()
{
return $this->work_year;
}
public function setWorkYear($year = 0)
{
$this->work_year = $year;
}
/**
* @return int
* 获取工资
*/
public function getSalary()
{
//通过发工资类的一个方法来计算工资
$this->salary = $this->payoff->pay($this);//谁调用获取工资的方法,$this就指向谁
return $this->salary;
}
}
//工资和工龄对应关系的类
class Payoff
{
//将上面的 Person 类定义为 $person
public function pay(Person $person)
{
$salary = 0;
$year = $person->getWorkYear();
if ($year <= 1) {
$salary = 1000;
} elseif ($year > 1 && $year <= 3) {
$salary = 2000;
} elseif ($year > 3) {
$salary = 5000;
}
return $salary;
}
}
$bob = new Person();
echo '工龄是:' . $bob->getWorkYear(), '年; 工资是:' . $bob->getSalary() . '元<br>';
$bob->setWorkYear(2);
echo '工龄是:' . $bob->getWorkYear(), '年; 工资是:' . $bob->getSalary() . '元<br>';
$bob->setWorkYear(3);
echo '工龄是:' . $bob->getWorkYear(), '年; 工资是:' . $bob->getSalary() . '元<br>';
$tom = new Person();
echo '工龄是:' . $tom->getWorkYear(), '年; 工资是:' . $tom->getSalary() . '元<br>';
$tom->setWorkYear(1);
echo '工龄是:' . $tom->getWorkYear(), '年; 工资是:' . $tom->getSalary() . '元<br>';
$tom->setWorkYear(6);
echo '工龄是:' . $tom->getWorkYear(), '年; 工资是:' . $tom->getSalary() . '元<br>';
php——16-面向对象实例(根据工龄发工资)
最新推荐文章于 2023-01-15 21:03:44 发布