Monday 28 July 2014

PHP Parse error: syntax error, unexpected '['

Encountered a strange PHP issue this morning when working on a client's server:

PHP Parse error:  syntax error, unexpected '['

The line in question was:

$intNumberOfChars = (int) substr(explode('(',$objField->DbDataType)[1],0,-1);



It turns out that PHP 5.3 and below (installed on the client's server) don't like to array dereference the result of a function or method call directly.  In essence, it means before PHP 5.4 you must use a temporary variable:

$arrTemporaryVariable = explode('(',$objField->DbDataType);
$intNumberOfChars = (int) substr($arrTemporaryVariable[1],0,-1);

I've never had this error before, so worth pointing out to people.  I'm amazed that the functionality has only been available since March 2012 (5.4's release date) as I use it all the time.


No comments:

Post a Comment