When I try to run something like

getParent($child)[0]->user

I get the following error:

PHP Parse error:  syntax error, unexpected '[', expecting ')' in /.....

The problem can be avoided if I do something like this:

$get_parent = getParent($child);
$parent = $get_parent[0]->user;

Is there a better way to do in php 5.3

有帮助吗?

解决方案

No, before PHP5.4, you have to do that.

Array dereferencing comes from PHP 5.4.

But if getParent return an object which implement the ArrayAccess interface, you could chain it with:

$parent = getParent($child)->offsetGet(0)->user;

If it just return an array, then a temp variable is necessary.

其他提示

Actually, there is a way to achieve that without temporary variable. But I definitely wouldn't recommend to use it (because, yes, it's one-liner and it's not using temporary variable, but no - it's not readable):

function getParent($child=null)
{
   //mock:
   return array(
      (object)(array('user'=>'foo', 'data'=>'fee')),
      (object)(array('user'=>'bar', 'data'=>'bee')),
   );
};

//array(null) will have 1 key, 0;
//however, to get another offset N, use array(N => null) instead
$result = array_shift(array_intersect_key(getParent('baz'), array(null)))->user;

-so use temporary variable if your version in <5.4

Where it may be helpful - is in debugger, where you're forced to use "one-liners" to check some expression(s)

There is no better way to do it when using PHP version < 5.4.

If you still want to use one line instead of 2 and you always want to get the first element, you can try the following

echo reset(getParent($child))->user;

This reset the array pointer to 0 and returns the value.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top