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 u盘问题:盘符不显示 无媒体
  • ¥50 R语言读取nc按月均值转为tif
  • ¥30 智能车串级pid调参
  • ¥15 visual studio code翻译老是错误
  • ¥20 卫星测高数据的高程转换
  • ¥15 爬取招聘网站数据信息
  • ¥15 安装完tensorflow,import tensorflow as tf后报错,如何解决?
  • ¥15 ultralytics库导出onnx模型,模型失去预测能力
  • ¥15 linux下点对点协议连接2个USB串口的硬件流量控制问题
  • ¥15 SQL数据自动生成问题