Combine an abstract class, subclasses and a trait to build a report in which each kind of employee is paid by its own rule.
What to build
A program that prints a payroll.
Requirements
- Write an abstract class
Employeewith a name and a base salary and an abstractpay(); a traitFormatswith a methodline()that returnsNAME (Type): PAY; and the subclassesManager,DeveloperandIntern. - Pay rules: a Manager gets base + 500; a Developer gets base + base / 10 (whole-number division); an Intern gets base / 2 (whole-number division).
- Read n, then n lines
type name basewith the type in lower case. Print one report line per employee. A line with another type printsunknown type TYPE. After all lines, printTotal: Tfor the valid employees.
Input
Line 1: n. Then n lines type name base.
Output
n + 1 lines.
Constraints
1 ≤ n ≤ 20; base is between 100 and 10000.
Example
Input:
3
manager Ann 3000
developer Bo 2500
intern Cy 1000
Output:
Ann (Manager): 3500
Bo (Developer): 2750
Cy (Intern): 500
Total: 6750
Why it works
Every subclass answers pay() in its own way, and the trait gives all of them the same line format without a second parent.
Examples
Example 1 · Input
3 manager Ann 3000 developer Bo 2500 intern Cy 1000
Expected output
Ann (Manager): 3500 Bo (Developer): 2750 Cy (Intern): 500 Total: 6750
Example 2 · Input
1 intern Dee 999
Expected output
Dee (Intern): 499 Total: 499
Hints
Hint 1
An abstract class Employee with an abstract pay() method; Manager, Developer and Intern extend it.
Hint 2
Put the shared formatting method line() in a trait and use it in Employee.
Solution
Show one correct solution (try it yourself first)
<?php
trait Formats
{
public function line(): string
{
return $this->name . " (" . static::class . "): " . $this->pay();
}
}
abstract class Employee
{
use Formats;
public function __construct(protected string $name, protected int $base)
{
}
abstract public function pay(): int;
}
class Manager extends Employee
{
public function pay(): int
{
return $this->base + 500;
}
}
class Developer extends Employee
{
public function pay(): int
{
return $this->base + intdiv($this->base, 10);
}
}
class Intern extends Employee
{
public function pay(): int
{
return intdiv($this->base, 2);
}
}
$n = (int) trim(fgets(STDIN));
$total = 0;
for ($i = 0; $i < $n; $i++) {
[$type, $name, $base] = explode(" ", trim(fgets(STDIN)));
$employee = match ($type) {
"manager" => new Manager($name, (int) $base),
"developer" => new Developer($name, (int) $base),
"intern" => new Intern($name, (int) $base),
default => null,
};
if ($employee === null) {
echo "unknown type $type\n";
continue;
}
echo $employee->line(), "\n";
$total += $employee->pay();
}
echo "Total: $total\n";