0
class date{
    public $now,$today;
    public function __construct(){
        $now = new DateTime("now");
        $today = new DateTime("today");
    }
}

$date= new date();
echo $date->$now->format('l, jS F Y, g:i A');

该代码无法正常工作并出现错误

注意:未定义的属性:date::$now

根据 OOP 概念,我需要在任何函数之外的类内部$now声明。$today但 php 不需要声明变量。

正确的方法是什么?

4

2 回答 2

2

您现在和今天将声明为构造函数的局部变量,而不是类的实例变量。然后您需要使用 $this 引用它们

class date{
    public $now;
    public $today;

    public function __construct(){
        $this->now = new DateTime("now");
        $this->today = new DateTime("today");
    }
}

您可能还想重命名该类,以免与内置日期方法混淆。

于 2013-08-14T02:53:39.717 回答
1

在这里,您在 php 中有正确的 OOP 形式:

<?php
class date{
        public $now;
        public $today;

        public function __construct(){
                $this->now = new DateTime("now");
                $this->today = new DateTime("today");
        }
}

$date= new date();
echo $date->now->format('l, jS F Y, g:i A');
?>
于 2013-08-14T02:58:52.360 回答