0

我正在寻找直接从对象的方法访问数组值的类型。

例如 :

使用这种语法,没问题:

$myArray = $myObject->getArray();

print_r($myArray[0])

但是为了减少源代码的行数,如何直接用方法获取元素呢?

我这样做了,但这是不正确的:

$myArray = $myObject->getArray()[0];
4

5 回答 5

3

以下内容仅适用于PHP 5.4及更高版本。

$myArray = $myObject->getArray()[0];

不幸的是,没有比 PHP 5.4 更快的方法了。

请参阅@deceze 的答案以获得一个不错的选择。

于 2012-07-05T08:16:16.673 回答
2

For PHP 5.3-:

$myArray = current($myObject->getArray());

or

list($myArray) = $myObject->getArray();
于 2012-07-05T08:18:18.297 回答
1

如果您使用的是 php 5.4(支持数组取消引用),您可以执行第二个选项:

$myArray = $myObject->getArray()[0];

如果您使用的是 PHP < 5.4,您可以在类中“修复”它(对象是一个实例):

class Foo
{
    public function getArray()
    {
        return $this->theArray;
    }

    public function getFirstItem()
    {  
         return $this->theArray[0];
    }
}

$myObject = new Foo();
print_r($myObject->getFirstItem());
于 2012-07-05T08:16:30.873 回答
1

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?

于 2012-07-05T08:21:10.713 回答
0

这是不可能的。

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!

于 2012-07-05T08:17:16.360 回答