Wednesday 25 January 2017

PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR



I got this error when debugging my code:




PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR in order.php on line 72





Here is a snippet of the code (starting on line 72):



$purchaseOrder = new PurchaseOrderFactory->instance();
$arrOrderDetails = $purchaseOrder->load($customerName);

Answer



Unfortunately, it is not possible to call a method on an object just created with new before PHP 5.4.



In PHP 5.4 and later, the following can be used:




$purchaseOrder = (new PurchaseOrderFactory)->instance();


In previous versions, you have to call the method on a variable:



$purchaseFactory = new PurchaseOrderFactory;
$purchaseOrder = $purchaseFactory->instance();


Note: The later is probably even more useful/wise even after you've upgraded to PHP 5.4 because those two lines can be better separated and there is less code containing a hard-encoded classname, here the name of the factory class PurchaseOrderFactory. This will make you more fluent maintaining the code over time.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...