tags:

views:

282

answers:

3

In PHP, this code works:

$usage = (package_manager_get_user_usage($uid));
$usage = $usage[email];

But this does not:

$usage = (package_manager_get_user_usage($uid))[email];

Why? They appear to be doing the same thing.

+7  A: 

That looks like a problem with PHP not being as object-oriented as you perhaps would like. Perhaps (package_manager_get_user_usage($uid)) does not evaluate to the associative array you require to access [email] on it inline. Some folks marked this as a bug: Bug #24978 PHP should allow access to object properties inline. That link suggests this functionality will be available in PHP5, which leads me to ask: what version of PHP are you using?

Sarah Vessels
It's not about being object-oriented, it's about being array-oriented ;-) Or, in fact, syntactically consistent. The object properties access works in php 5 just fine, but not array subscripts. And yes, this is stupid of php.
Michael Krelin - hacker
No OO involved. It means that you need a variable to access an array element, it cannot be done from the return of a function even if this contains an array. Most likely this is caused by the fact that there is weak type checking in PHP and therefore the syntax check cannot know if the return value would be an array or not. Yes, the check could be done in runtime, but that is after the syntax check.
txwikinger
i am using php5.
RD
txwikinger, I think it's just phpish and there's no excuse beyond something like "too much hassle to implement". After all the function can return object and you can access its properties, although parser has no idea whether the function returns object or integer.
Michael Krelin - hacker
@hacker: Well.. I did not say, it could not be done. I am just saying that there is a certain philosophy behind the language and therefore some things are simple and some are complicated to implement.
txwikinger
+3  A: 

If $usage is an array, PHP does not allow you to directly access its elements when it's called. Instead something like this would be more appropriate:

list($usage) = package_manager_get_user_usage($uid);
//Assuming that the first element returned is the one you are trying to access.

And is email defined as some constant in your code? If not, you need to wrap it some quotes.

This question is somewhat related: http://stackoverflow.com/questions/13109/php-access-array-value-on-the-fly

Sam152
Well.. only remotely.
txwikinger
Whoops, wrong question. Updated.
Sam152
+2  A: 

PHP simply has no such syntax like other languages do. In PHP that array-like accessing syntax is only allowed when used together with variables.

This feature was requested but unfortunately it was decliend.

Gumbo