直接从数组返回函数引用数组元素(php)

时间:2013-03-25 20:08:51

标签: php arrays

return array(
    'client_id' => $client[0]->getId(),
    'client secret' =>  $client[0]->getSecret(),
    'redirect_uri' =>  ($client[0]->GetClientEndpoints())[0]->getRedirectUri(),
    'name' =>  $client[0]->getName());

特别是片段:

($client[0]->GetClientEndpoints())[0]->getRedirectUri()

有没有办法,我可以做到这一点,而不必这样做:

 $endpoints = $client[0]->GetClientEndpoints();
 return array(
    'client_id' => $client[0]->getId(),
    'client secret' =>  $client[0]->getSecret(),
    'redirect_uri' =>  $endpoints[0]->getRedirectUri(),
    'name' =>  $client[0]->getName());

2 个答案:

答案 0 :(得分:2)

$client[0]->GetClientEndpoints()[0]->getRedirectUri()应该在PHP 5.4中运行。还没有5.4吗?你需要更新。

虽然它非常难看,而且不太可读。我会:

$client = $client[0];
$endpoint = $client->GetClientEndpoints()[0];
return array(....

答案 1 :(得分:1)

我不确定它是否有用,但也许你可以试试

http://www.php.net/manual/en/function.array-shift.php

return array(
    'client_id' => $client[0]->getId(),
    'client secret' =>  $client[0]->getSecret(),
    'redirect_uri' =>  array_shift($client[0]->GetClientEndpoints())->getRedirectUri(),
    'name' =>  $client[0]->getName());

至少此代码段没有任何错误:

<?php
error_reporting(E_ALL);

class class1{
    public function getRedirectUri()
    {
        return 'something';
    }
}

$arr1 = array(new class1(), new class1());

$arr = array(
    'client_id' => 'something',
    'client secret' =>  'something',
    'redirect_uri' =>  array_shift($arr1)->getRedirectUri(),
    'name' =>  'something');

更新(感谢Rudie

事实证明,上面的示例与作者的情况不同,所以一个更好的例子(抛出E_STRICT,因此我的答案不应该被考虑)是:

<?php
error_reporting(E_ALL);

class class2{
    public function getRedirectUri()
    {
        return 'something';
    }
}

class class1 {
    public function getArrays() {
        return array(new class2(), new class2());
    }
}
$var = new class1 ();

$arr = array(
    'client_id' => 'something',
    'client secret' =>  'something',
    'redirect_uri' =>  array_shift($var->getArrays())->getRedirectUri(),
    'name' =>  'something');