3

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');
BlackNetworkBit
  • 768
  • 11
  • 21
SL5net
  • 2,282
  • 4
  • 28
  • 44
  • [Yes, you can.](http://3v4l.org/0FAFK) – Amal Murali Nov 22 '13 at 14:47
  • @sl5net: if you wish to comment on answer, use comments, don't edit answers like [this](http://stackoverflow.com/review/suggested-edits/3418460). Btw: don't use `@` infront of date_create() call, no need for that ([demo](http://3v4l.org/EK15B)). – Glavić Nov 22 '13 at 17:49
  • isn't simple time() the shortest way? http://php.net/manual/en/function.time.php – Łukasz Rysiak Aug 30 '16 at 06:03

4 Answers4

8

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();
Glavić
  • 42,781
  • 13
  • 77
  • 107
1

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.

Community
  • 1
  • 1
daxeh
  • 1,083
  • 8
  • 12
0

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

deceze
  • 510,633
  • 85
  • 743
  • 889
-1

As of PHP 5.4, you can write

echo (new DateTime())->getTimestamp();
l-x
  • 1,521
  • 9
  • 17