2012-04-17 58 views
2

是否可以在一行中调用返回数组()并直接获取此数组的值的方法?直接显示由方法返回的数组的值

例如,而不是:

$response = $var->getResponse()->getResponseInfo(); 
$http_code = $response['http_code']; 
echo $http_code; 

做这样的事情:

echo $var->getResponse()->getResponseInfo()['http_code']; 

这个例子不工作,我得到一个语法错误。

+0

应该是好的,虽然我不知道调用“两个”方法; $ var-> getResponse() - > getResponseInfo ..不应该那些理想地分开? – Bono 2012-04-17 11:18:49

+0

我问了同样的问题,它被关闭为http://stackoverflow.com/questions/2396782/parse-error-on-explode-foo-bar0-for-instance :( – 2012-04-17 11:27:40

回答

1

你可以做的是直接传递给你的函数。你的函数应该是这样的,如果一个变量名被传递给它,它应该是该变量的值,否则是一个包含所有变量值的数组。

你可以做到这一点是:

<?php 
// pass your variable to the function getResponseInfo, for which you want the value. 
echo $var->getResponse()->getResponseInfo('http_code'); 
?> 

您的功能:

<?php 
// by default, it returns an array of all variables. If a variable name is passed, it returns just that value. 
function getResponseInfo($var=null) { 
    // create your array as usual. let's assume it's $result 
    /* 
     $result = array('http_code'=>200,'http_status'=>'ok','content_length'=>1589); 
    */ 

    if(isset($var) && array_key_exists($var, $result)) { 
     return $result[ $var ]; 
    } else { 
     return $result; 
    } 
} 
?> 

希望它能帮助。

4

如果您使用> = PHP 5.4,您可以。

否则,您将需要使用新变量。

1

语言本身不支持数组。

如果你可以改变什么getResponseInfo()返回:

您可以创建简单的类,这将有数组作为构造函数的参数。然后定义magical getter将从实例阵列

function __get($key) 
{ 
    return @content[$key] 
} 

只是拉键然后你就可以做

echo $var->getResponse()->getResponseInfo()->http_code; 
// or 
echo $var->getResponse()->getResponseInfo()->$keyWhichIWant; 

我写的仅仅是建议。真正__get方法应该有一些检查,如果存在等等