0

I don't really need to store DateTime object. Would be possible to call modify anonymously? I've tried:

$passwordRequest->setExpire((new \DateTime())->modify('+12 hours'));

But can't get it to work. Am i asking for the moon?

hakre
  • 193,403
  • 52
  • 435
  • 836
gremo
  • 47,186
  • 75
  • 257
  • 421
  • 1
    This is currently under discussion for inclusion: https://wiki.php.net/rfc/instance-method-call – Gordon Nov 18 '11 at 22:17

3 Answers3

2

In this particular instance, you can use date_modify() instead like so:

passwordRequest->setExpire(date_modify(new DateTime(), '+12 hours'));

Testing:

var_dump(date_modify(new DateTime(), '+12 hours'));

object(DateTime)#2 (3) {
  ["date"]=>
  string(19) "2011-11-19 04:16:04"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(15) "America/Chicago"
}

As mentioned in the linked duplicate question, you cannot chain methods off a new instantiation.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Thank you. Not the right answer (php doesn't support chaining) but i'm going to use this. – gremo Nov 18 '11 at 22:24
0

It's a limitation of PHP (I see it as one anyway) that you must call methods on a variable. In other words, what you're trying to do is not possible.

Corbin
  • 33,060
  • 6
  • 68
  • 78
0

According to PHP, it looks like you can call modify() statically, but I tried it and it won't work. Looks like DateTime needs to be insantiated because the constructor takes a date.

// According to PHP looks like it should work, but doesn't
$passwordRequest->setExpire((DateTime::modify('+12 hours'));

// Notice I have to pass a date to the construct when I instantiate
$date = new DateTime('2006-12-12');
$date->modify('+1 day');

A better implementation would be to make modify() static with two args, one for the date, and one for the time adjust, something like:

public static function modify($timeAdjust, $time = time()) 
Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
  • All methods in the manual are listed as `ClassName::methodName`. This does not imply static method. Static methods have the `static` keyword in the method signature, cf. http://php.net/manual/en/datetime.createfromformat.php – Gordon Nov 18 '11 at 22:22
  • Figured it was a naming convention, was worth a shot though. – Mike Purcell Nov 18 '11 at 22:24