-2

我创建了 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";
?>

它只输出

[newline]
[newline]
Hello

我将 __construct() 更改为此

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

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

编辑:对不起我的错误。我输入了 this->$day 而不是 $this->day

4

5 回答 5

7

您没有正确引用变量,您需要使用

$this->day;
$this->month;
$this->year;

尝试将您的课程更新为此

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;
    }
}
于 2013-04-02T16:42:46.370 回答
6

您的 OOP 不正确:

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

注意$在作业中的位置。

于 2013-04-02T16:42:33.057 回答
4

您的类函数和构造函数缺少$this->变量以表明它们是类的一部分,而不是在函数内本地设置。:

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;
}
于 2013-04-02T16:42:54.823 回答
3

这是你的变量引用,$在第一个对象引用之前,而不是在成员引用之前:

public function __construct($dy, $mon, $yar){
    $this->day = $dy;
    $this->month = $mon;
    $this->year = $yar;
}
于 2013-04-02T16:42:24.160 回答
3

您需要正确引用您的类变量。例如:

echo $this->day;

这需要对类中的每个类变量进行。

于 2013-04-02T16:42:25.103 回答