SL5net
SL5net

Reputation: 2566

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

Upvotes: 3

Views: 21399

Answers (4)

l-x
l-x

Reputation: 1571

As of PHP 5.4, you can write

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

Upvotes: -1

daxeh
daxeh

Reputation: 1085

Also, if default timezone is not set, add the following at in the top of your adhoc script otherwise set default timezone in php.ini for global settings.

date_default_timezone_set('Australia/Sydney'); // set it your timezone

Hope this helps.

Upvotes: 1

Glavić
Glavić

Reputation: 43572

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

Upvotes: 8

deceze
deceze

Reputation: 522321

That syntax is supported since PHP 5.4. In older versions you'll indeed have to assign the object to an intermediate variable.

Upvotes: 0

Related Questions