Matthijs2504 Matthijs2504 - 6 months ago 15
AngularJS Question

(PHP) Check for valid day and month combination

Evening!

I'm trying to learn OO-programming in PHP and I want to check if a given day is valid in a given month. For example: 01-31-2016 is valid (because January has 31 days), 04-31-2016 is invalid (because April has only 30 days). I figured this can be done with

checkdate()
, but I'm struggling to make this work.

This is what I got so far:

<?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();
?>


I think I'm not using the checkdate function in the right way, but I can't figure it out. If the date is valid, the date should be printed. If the date is invalid,
$temp
should be printed. However, currently every date gets printed, whether it be valid or invalid. What am I doing wrong?

Answer

It looks like the only problem is, that you don't call setBirthdate() in your Constructor.

Edit: So like TheDrot said, this should work:

<?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();
?>