randomKek
randomKek

Reputation: 1128

php variable array name

I got the following class and I want to know if it is possible to use a variable array name.

class Ajax{
    private $method;

    public function __construct(){
        $this->method = '$_' . $_SERVER['REQUEST_METHOD'];
    }
}

So basically the $method variable should either contain the POST or GET method, next question is also if it is smart to use a reference here?

My first thought was:

$this->method = '$_' . $_SERVER['REQUEST_METHOD'];
$this->metod =& $$this->method;

But that is not working.

Thanks for reading and help, much appreciation.

Upvotes: 0

Views: 150

Answers (3)

aletzo
aletzo

Reputation: 2491

try to get it like this:

$this->method = ${'_' . $_SERVER['REQUEST_METHOD']};

Upvotes: 1

xdazz
xdazz

Reputation: 160863

Why not just do

If ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $this->method = $_GET;
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $this->method = $_POST;
}

If you want to directly work, then

$this->method = ${'_'.$_SERVER['REQUEST_METHOD']};

OR you can just use the $_REQUEST (although it is not very good to use it)

$this->method = $_REQUEST;

Upvotes: 1

Marc B
Marc B

Reputation: 360702

You'd want something like

    $this->method = $$_SERVER['REQUEST_METHOD'];

this being a "variable variable" (note the double $$). However, please don't do this. variable variables make for difficult-/impossible-to-debug code.

Upvotes: 1

Related Questions