2

Is it possible to do in one line calling a method that returns an array() and directly get a value of this array ?

For example, instead of :

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

Do something like this :

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

This example does not work, I get a syntax error.

ncrocfer
  • 2,542
  • 4
  • 33
  • 38
  • Should be allright, although I'm not sure about calling "two" methods; $var->getResponse()->getResponseInfo.. Shouldnt those ideally be apart? – Bono Apr 17 '12 at 11:18
  • I asked the same question and it was closed as a duplicate of http://stackoverflow.com/questions/2396782/parse-error-on-explode-foo-bar0-for-instance :( – Salman A Apr 17 '12 at 11:27

3 Answers3

4

If you're using >= PHP 5.4, you can.

Otherwise, you'll need to use a new variable.

alex
  • 479,566
  • 201
  • 878
  • 984
1

What you can do is to pass the directly to your function. Your function should be such that if a variable name is passed to it, it should the value of that variable, else an array with all variables values.

You can do it as:

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

Your function:

<?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;
   }
}
?>

Hope it helps.

web-nomad
  • 6,003
  • 3
  • 34
  • 49
1

Language itself does not support that for an array.

In case you can change what getResponseInfo() return:

You can create simple class, which will have array as an constructor parameter. Then define magical getter which will be just pulling the keys from the instance array

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

Then you'll be able to do

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

What i wrote is just proposal. The real __get method should have some check if the exists and so

Mailo Světel
  • 24,002
  • 5
  • 30
  • 40