Reputation: 1837
I'm looking for the kind to access at the value of an array directly from the object's method.
For example :
With this syntax, no problem :
$myArray = $myObject->getArray();
print_r($myArray[0])
But to reduce the number of line in source code, how to get the element directly with the method ?
I do that, but it's not correct :
$myArray = $myObject->getArray()[0];
Upvotes: 0
Views: 54
Reputation: 6617
The following is only available for PHP 5.4 and supposedly higher.
$myArray = $myObject->getArray()[0];
Unfortunately there is no quicker way below PHP 5.4.
See @deceze's answer for a good alternative.
Upvotes: 3
Reputation: 18859
But to reduce the number of line in source code, how to get the element directly with the method ?
Although it is possible to achieve this in PHP 5.4 with the syntax you've demonstrated, I have to ask, why would you want that? There are ways of doing it in 5.3 in a one-liner, but I don't see the need to do this. The number of lines is surely less interesting than the readability of the code?
Upvotes: 1
Reputation: 522135
For PHP 5.3-:
$myArray = current($myObject->getArray());
or
list($myArray) = $myObject->getArray();
Upvotes: 2
Reputation: 15047
IT IS IMPOSSIBRRUUU.
Serious answer: sadly it is not possible. You can write a very ugly wrapper like this:
function getValue($arr, $index)
{
return $arr[$index];
}
$myArray = getValue($myObject->getArray(), 0);
But that makes less readable code.
read other answers about php 5.4 Finally!
Upvotes: 0
Reputation: 72682
If you are on php 5.4 (which support array dereferencing) you can do the second option:
$myArray = $myObject->getArray()[0];
If you are on PHP < 5.4 you can "fix" it in the class (of which the object is a instance):
class Foo
{
public function getArray()
{
return $this->theArray;
}
public function getFirstItem()
{
return $this->theArray[0];
}
}
$myObject = new Foo();
print_r($myObject->getFirstItem());
Upvotes: 1