PHP 抽象メソッド

<?php
abstract class Score
{
    private $subject;
    protected $points;

    public function __construct($subject, $points)
    {
        $this->subject = $subject;
        $this->points = $points;
    }

    abstract protected function getResult();

    public function getInfo()
    {
        return "{$this->subject}, {$this->points}, {$this->getResult()}";
    }
}

class MathScore extends Score
{
    public function __construct($points)
    {
        parent::__construct("Math", $points);
    }

    // protected function getResult()
    // {
    //     echo "MathScore method" . PHP_EOL;
    //     return $this->points >= 50 ? "Pass" : "Fail";
    // }
}

class EnglishScore extends Score
{
    public function __construct($points)
    {
        parent::__construct("English", $points);
    }

    protected function getResult()
    {
        echo "EnglishScore method" . PHP_EOL;
        return $this->points >= 95 ? "Pass" : "Fail";
    }
}

class User
{
    private $name;
    private $score;

    public function __construct($name, $score)
    {
        $this->name = $name;
        $this->score = $score;
    }

    public function getInfo()
    {
        return "{$this->name}, {$this->score->getInfo()}";
    }
}

$user1 = new User("Taro", new MathScore(70));
$user2 = new User("Jiro", new EnglishScore(90));

echo $user1->getInfo() . PHP_EOL;
echo $user2->getInfo() . PHP_EOL;

投稿者: chosuke

趣味はゲームやアニメや漫画などです

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です