一个类在另一个类中的对象


Object of a class inside another class

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');

代码无法正常工作,但错误

注意:未定义的属性:日期::$now

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

正确的方法是什么?

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

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

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

这里有 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');
?>