LoginSignup
0
0

More than 1 year has passed since last update.

PHPで5の付く日曜日を出力するプログラム

Posted at

実務で3ヶ月経過したので4ヶ月前に書いたのと同じものを作ってみました
↓↓Javaで5の付く日曜日を出力するプログラム
https://qiita.com/noczz/items/aa1caccf6aebc334b0f8

今見返すと酷いコードですね…
初心者なりに前よりも良いコードを書けるように考えてみました
実務ではPHPを触っていますのでPHPで書いてみました

プログラム要件

  • endと入力されるまで無限ループ
  • Enterキーを押すと1つずつ次の5のつく日曜日の年月日が表示される

<?php
const SPECIAL_DAYS = 5;

class BlarDateTime extends DateTime
{
    /**
     * Return Date in ISO8601 format
     *
     * @return String
     */
    public function __toString()
    {
        return $this->format('Y-m-d');
    }

    /**
     * SPECIAL_DAYSの付く日曜日を返す
     * 次の日曜日の日付にSPECIAL_DAYSが含まれていなければ再帰処理
     * @return String
     */
    public function getNextSpecialDays()
    {
        if (strpos($this->modify('next Sunday')->format('d'), SPECIAL_DAYS) == True) {
            return $this->format('Y-m-d');
        }
        return $this->getNextSpecialDays();
    }
}

echo '現在の日付から5のつく日曜日を表示します…'. PHP_EOL;
echo 'Enterキーを押すと次の日付を表示'. PHP_EOL;
echo 'endと入力するとループ終了'. PHP_EOL;

$date = new BlarDateTime();

while (true) {
    $input = trim(fgets(STDIN));
    if ($input == 'end') {
        return;
    }
    echo $date->getNextSpecialDays();
}
?>
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0