tags:

views:

143

answers:

4

Why is it not possible to do something equivalent to this in PHP:

(Array(0))[0];

This is just for sake of argument, but it seems strange it does not allow access of anonymous objects. I would have to do something like the following:

$array = Array(0);
$array[0];

Any ideas why this is the behavior of PHP?

+1  A: 

I guess the short answer is: nobody has coded it yet. I've used (and loved) that syntax in both Python and Javascript, but still we wait for PHP.

Adam Backstrom
+4  A: 

I read something somewhat detailed about this once and I regret not bookmarking it because it was quite insightful. However, it's something along the lines of

"Because the array does not exist in memory until the current statement (line) executes in full (a semicolon is reached)"

So, basically, you're only defining the array - it's not actually created and readable/accessible until the next line.

I hope this somewhat accurately sums up what I only vaguely remember reading many months ago.

Peter Bailey
Shame you can't remember the URL
Jotham
A: 

The main reason is because unlike some languages like Python and JavaScript, Array() (or in fact array()) is not an object, but an language construct which creates an inbuilt data type. Inbuilt datatypes themselves aren't objects either, and the array() construct doesn't return a reference to the "object" but the actual value itself when can then be assigned to a variable.

Wesley Mason
+3  A: 

This language feature hasn’t been inplemented yet but will come in PHP 6.

Gumbo