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

时间:2013-04-02 16:40:42

标签: 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";
?>

只输出

[newline]
[newline]
Hello

我将__construct()更改为此

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

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

编辑:抱歉我的错误。我输入了这个 - &gt; $ day而不是$ this-&gt; day

5 个答案:

答案 0 :(得分:6)

您的OOP不正确:

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

请注意$在作业中的位置。

答案 1 :(得分:6)

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

$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;
    }
}

答案 2 :(得分: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;
}

答案 3 :(得分:3)

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

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

答案 4 :(得分:3)

您需要正确引用类变量。 E.g:

echo $this->day;

这需要在你班级的每个班级变量中完成。