duang8642 2013-04-02 16:40 采纳率: 0%
浏览 169
已采纳

PHP:为什么类构造函数不起作用? [关闭]

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

  • 写回答

5条回答 默认 最新

  • dongyinglan8707 2013-04-02 16:42
    关注

    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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题