views:

74

answers:

2
$method = 'post';

$method = strtoupper($method);
echo $method.'test1';

$method = '_'.$method;
echo $method.'test2';

$method = $$method;
echo $method.'test3';

Why doesn't this print the content of $_POST between 2 and 3?

+1  A: 

You want $method['test3'] to access the elements of the $_POST array. The dot . operator does string concatenation. Square brackets [] are used for array access.

John Kugelman
No, I want $_SESSION, $_COOKIE, $_POST and $_GET from 'session', 'cookie', 'post' and 'get'.
Delirium tremens
I think I'm going to end up usingif($method == 'post') $method = $_POST;if($method == 'get') $method = $_GET;if($method == 'session') $method = $_SESSION;if($method == 'cookie') $method = $_COOKIE;
Delirium tremens
+1  A: 

In addition to John Kugelman's excellent point, I would use the following

$method = $_POST;

echo $method['test1'];

echo $method['test2'];

echo $method['test3'];

and not bother with trying to access a contant array name via a string

If you really insist on using a string to access these, you could

$method = "post";
$method = strtoupper($method."_");    
if (isset(${$method})) {
  $method = ${$method};

  echo $method['test1'];

  echo $method['test2'];

  echo $method['test3'];
}
Jonathan Fingland
Missing the quotes around the array indexes, that's almost -1 worthy...
Paolo Bergantino
thanks Paolo. fixed
Jonathan Fingland