简体   繁体   中英

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

The code is not working with error

Notice: Undefined property: date::$now

As per OOP concept i need to declare $now and $today inside the class outside any function. but php doesn't need declaration of variables.

What's the correct method?

You are declaring now and today as local variables to the constructor function, not instance variables of the class. You need to then reference them using $this

class date{
    public $now;
    public $today;

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

You might also want to rename that class so it's not confused with the built in date method.

Here you have the correct form of OOP in php:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM