(PHP)检查有效的日期和月份组合

时间:2016-05-18 22:58:26

标签: php

晚间!

我试图在PHP中学习OO编程,我想检查给定的一天在给定的一个月内是否有效。例如:01-31-2016有效(因为1月有31天),2016年4月31日无效(因为4月只有30天)。我认为这可以通过checkdate()来完成,但我很难努力做到这一点。

这是我到目前为止所得到的:

<?php
class birthDate {
 public $birthday;
 public $birthmonth;
 public $birthyear;

 public function __construct($birthday, $birthmonth, $birthyear) {
    $this->birthday = $birthday;
    $this->birthmonth = $birthmonth;
    $this->birthyear = $birthyear;
}

 public function setBirthdate($birthday, $birthmonth, $birthyear) {
    if (checkdate($birthmonth, $birthday, $birthyear) == TRUE) {
        $this->birthday = $birthday;
        $this->birthmonth = $birthmonth;
        $this->birthyear = $birthyear;
    } else {
        $birthday = 0;
        $birthmonth = 0;
        $birthyear = 0;
  }
}

 public function getBirthdate() {
    if ($this->birthday == 0 && $this->birthmonth == 0 && $this->birthyear == 0) {
        $temp = "Not possible";
  } else {
        $temp  = $this->birthday   . "-";
        $temp .= $this->birthmonth . "-";
        $temp .= $this->birthyear;  
  }
return $temp;
}

 public function printBday() {
    echo "<strong>Birthday: \t</strong>" . $this->getBirthdate();
  }
}

$date = new birthDate(4, 31, 1991);
$date->printBday();
?>

我认为我没有以正确的方式使用checkdate功能,但我无法弄明白。如果日期有效,则应打印日期。如果日期无效,则应打印$temp。但是,目前每个日期都会打印,无论是有效还是无效。我做错了什么?

2 个答案:

答案 0 :(得分:2)

看起来唯一的问题是,您不能在构造函数中调用setBirthdate()

编辑:就像TheDrot说的那样,这应该有效:

<?php
class birthDate {
 public $birthday;
 public $birthmonth;
 public $birthyear;

 public function __construct($birthday, $birthmonth, $birthyear) {
    $this->setBirthdate($birthday, $birthmonth, $birthyear);
}

 public function setBirthdate($birthday, $birthmonth, $birthyear) {
    if (checkdate($birthmonth, $birthday, $birthyear) == TRUE) {
        $this->birthday = $birthday;
        $this->birthmonth = $birthmonth;
        $this->birthyear = $birthyear;
    } else {
        $this->birthday = 0;
        $this->birthmonth = 0;
        $this->birthyear = 0;
  }
}

 public function getBirthdate() {
    if ($this->birthday == 0 && $this->birthmonth == 0 && $this->birthyear == 0) {
        $temp = "Not possible";
  } else {
        $temp  = $this->birthday   . "-";
        $temp .= $this->birthmonth . "-";
        $temp .= $this->birthyear;  
  }
return $temp;
}

 public function printBday() {
    echo "<strong>Birthday: \t</strong>" . $this->getBirthdate();
  }
}

$date = new birthDate(4, 31, 1991);
$date->printBday();
?>

答案 1 :(得分:1)

或者只是你可以像这样使用checkdate

bool checkdate ( int $month , int $day , int $year )
  

<强>参数

     

:月份介于1到12之间。

     

:该日期在给定月份的允许天数内。   闰年被考虑在内。

     

:年份介于1到32767之间。

  

返回值

     

如果给定的日期有效,则返回TRUE;否则返回 FALSE

$info1 = checkdate(4, 30, 1991);
var_dump($info1);

bool(true)如果日期有效

$info2 = checkdate(4, 31, 1991);
var_dump($info2);

bool(false)如果日期无效