I created Date() class. But it is not giving the desired outputs.
My code
<?php
class Date{
public $day = 1;
public $month = "January";
public $year = 2013;
public function __construct($dy, $mon, $yar){
$this->day = $dy;
$this->month = $mon;
$this->year = $yar;
}
public function lessthan($dt){
if($year != $dt->year)
return $year - $dt->year;
if($month != $dt->month)
return $month - $dt->month;
return $day - $dt->day;
}
public function pr(){
echo $day;
echo "<br>";
echo $month;
return;
}
}
$a = new Date(1,"January",2002);
$b = new Date(1,"January",2002);
$a->pr();
$b->pr();
echo "Hello";
?>
It only outputs
[newline]
[newline]
Hello
I changed the __construct() to this
public function __construct($dy, $mon, $yar){
this->$day = $dy;
this->$month = $mon;
this->$year = $yar;
}
But the output is still same. What is the mistake ?
EDIT : sorry for my mistake . i typed this->$day instead of $this->day
You aren't referencing the variables correctly, you need to use
$this->day;
$this->month;
$this->year;
try updating your class to this
class Date{
public $day = 1;
public $month = "January";
public $year = 2013;
public function __construct($dy, $mon, $yar){
$this->day = $dy;
$this->month = $mon;
$this->year = $yar;
}
public function lessthan($dt){
if($this->year != $dt->year)
return $this->year - $dt->year;
if($this->month != $dt->month)
return $this->month - $dt->month;
return $this->day - $dt->day;
}
public function pr(){
echo $this->day;
echo "<br>";
echo $this->month;
return;
}
}
It's your variable references, the $
goes before the first object reference, and not before the member references:
public function __construct($dy, $mon, $yar){
$this->day = $dy;
$this->month = $mon;
$this->year = $yar;
}
You need to reference your class variables correctly. E.g.:
echo $this->day;
This needs to be done with every class variable in your class.
Your OOP is incorrect:
public function __construct($dy, $mon, $yar) {
$this->day = $dy;
$this->month = $mon;
$this->year = $yar;
}
Note the placement of the $
in the assignments.
Your class functions and construct function are missing the $this->
variable to show that they are part of the class and not locally set inside the function.:
public function __construct($dy, $mon, $yar){
$this->day = $dy;
$this->month = $mon;
$this->year = $yar;
}
public function pr(){
echo $this->day;
echo "<br>";
echo $this->month;
return;
}