Why can't I access DateTime->date in PHP's DateTime class?

前端 未结 5 1563
醉梦人生
醉梦人生 2020-11-22 06:44

Using the DateTime class, if I try to run the following code:

$mydate = new DateTime();
echo $mydate->date;

I\'ll get back

5条回答
  •  北海茫月
    2020-11-22 07:10

    As noted by the other answers, it is an issue with PHP which is unresolved as of today but if it is a 'side effect' of var_dump() I am not so sure..

    echo ((array) new DateTime())['date']; // Works in PHP 7.
    

    What I am sure about is that if the properties of DateTime where meant to be used by us it would have been made available. But like many internal classes they are not and you shouldn't rely on "hacky" or "glitchy" methods to fix your code. Instead you should use their API.

    echo (new DateTime())->format('Y-m-d H:i:s');
    

    If you are not satisfied you can extend the class or perhaps use Carbon that extends it for you.

    echo (new Carbon())->toDateTimeString();
    

    If you wounder how var_dump() creates a fake output of an object take a look at __debugInfo()

提交回复
热议问题