phpdatetimeanonymous-objects

echo (new DateTime())->getTimestamp(); ... anonymous object not suported?


There is probably no way to do work with anonymous objects?

I want to do short thinks like this:

echo (new DateTime())->getTimestamp();

In javascript we could shortly use:

alert( (new Date()).getTime() );

Is there any shorter way which can be used in php?

Without creating a function?

Dont wanna use a exta funktion .. for eg:

function timestamp() {
    $dt = new DateTime();
    return $dt->getTimestamp();
}

BTW: useful links: https://www.google.de/search?q=php+creating+anonymous+object BTW2: this works:

$obj = (object) array('foo' => 'bar', 'property' => 'value');
echo $obj->foo;

Thanks all ! for your nice fast answers.

BTW3 (update from 13-11-22_16-12):

I found something useful also:

echo $_SERVER['REQUEST_TIME'];
echo @date('H:i:s');

Solution

  • Shorter than:

    echo (new DateTime())->getTimestamp();
    // or
    echo (new DateTime)->getTimestamp();
    # available in PHP >= 5.4.0
    

    would be to use procedural style (or mix between object and procedural):

    echo date_create()->getTimestamp();
    # available in PHP >= 5.3.0
    
    echo date_create()->format('U');
    # available in PHP >= 5.2.0
    

    or:

    echo time();