PHP:为什么类构造函数不起作用?

pal*_*tok -3 php

我创建了Date()类.但它没有给出理想的输出.
我的代码

<?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";
?>
Run Code Online (Sandbox Code Playgroud)

它只输出

[newline]
[newline]
Hello
Run Code Online (Sandbox Code Playgroud)

我将__construct()更改为此

public function __construct($dy, $mon, $yar){
        this->$day = $dy;
        this->$month = $mon;
        this->$year = $yar;
    }
Run Code Online (Sandbox Code Playgroud)

但输出仍然相同.这是什么错误?

编辑:抱歉我的错误.我键入了这个 - > $ day而不是$ this-> day

Mar*_*c B 6

你的OOP不正确:

public function __construct($dy, $mon, $yar) {
   $this->day = $dy;
   $this->month = $mon;
   $this->year = $yar;
}
Run Code Online (Sandbox Code Playgroud)

请注意$分配中的位置.

  • 你必须在所有方法中使用"$ this-> day".`$ day`本身就是这些方法中的局部变量.`$ this-> day`是对象的一个​​属性. (3认同)

Spr*_*gie 6

您无需正确引用变量,需要使用

$this->day;
$this->month;
$this->year;
Run Code Online (Sandbox Code Playgroud)

尝试将您的课程更新为此

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;
    }
}
Run Code Online (Sandbox Code Playgroud)