Search code examples
phpsyntaxphp-5.4

Direct access class member access with clone


As of PHP 5.4 we can use this kind of syntax:

$oYesterday = (new \DateTime())->modify('-1 day');

So we don't have to create a temp variable. I was wondering why it doesn't work with clone, it leads to a parse error:

$oDayBefore = (clone $oYesterday)->modify('-1 day');

PHP Parse error:  syntax error, unexpected '->' (T_OBJECT_OPERATOR)

Solution

  • Because in PHP < 7, everything in the parser was essentially a hard-coded special case, and nobody has bothered to write the case for (clone $var). PHP 7 finally sports a real AST, where such things are possible.