0

Possible Duplicate:
PHP syntax for dereferencing function result

If a PHP function returns an array, the following syntax will not work:

$firstValue = $object->methodThatReturnsArray()[0]; // syntax error, unexpected '['

This, however, works fine:

$temporaryArray = $object->methodThatReturnsArray(); 
$firstValue = $temporaryArray[0]; // temporary will never be reused

What is the best syntax to solve this problem, or is creating that variable the recommended approach?

Community
  • 1
  • 1
tucuxi
  • 17,561
  • 2
  • 43
  • 74

2 Answers2

2

Variable is the best approach.

Still PHP 5.4 adds the feature to be able using the first mentioned syntax.

Gedrox
  • 3,592
  • 1
  • 21
  • 29
  • See http://www.php.net/archive/2011.php#id2011-06-28-1 change titled "Array dereferencing support". More about this change can be read in http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html. – Gedrox Jul 04 '11 at 13:34
  • @yes123 http://www.php.net/releases/NEWS_5_4_0_alpha1.txt - General improvements: Added array dereferencing support – Yoshi Jul 04 '11 at 13:35
  • thanks - will accept after a few minutes. Frustrating because it is common syntax in many C-like languages. @yes123: feature is announced for 5.4, just checked. – tucuxi Jul 04 '11 at 13:35
  • oh god. they are getting ready for php 6: `Changed default value of "default_charset" php.ini option from ISO-8859-1 to UTF-8` – dynamic Jul 04 '11 at 13:50
  • do you know when something like this will be accepted? https://wiki.php.net/rfc/instance-method-call `new Object()->method();` – dynamic Jul 04 '11 at 13:54
0

Well, you can have list to the left of the = (list($firstValue) = $object->methodThatReturnsArray();), if you need anything too deep in the array, a temporary variable is your only option.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166