问题描述:

I'm working on a web library for personal use. I thought I'd be all clever and use variable variables to make my library support all request methods easily.

I had:

$request = '_' . $_SERVER['REQUEST_METHOD'];

$request = $$request;

But I get:

Undefined variable: _POST

Printed to my php error log.

I was just curious as to whether my idea is flawed conceptially, as well as why the logic fails to work when the following does:

$_a = 'b';

$b = '_a';

$c = $$b;

Edit:

The following does work:

$request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

Duplicate of:

Superglobals can't be accessed via variable variables in a function?

To fix I did:

$request = $GLOBALS['_' . $_SERVER['REQUEST_METHOD']];

You could also use my original code outside of a function or class.

网友答案:

The error message you are getting is correct, there is no such variable as $_POST.

$request = '_' . $_SERVER['REQUEST_METHOD'];

Let's assume $_SERVER['REQUEST_METHOD'] is "POST" which it will be for an HTTP POST request.

Therefore $request == "_POST"

$request = $$request;

i.e. $request = $_POST;

What is it exactly you're trying to achieve here?

网友答案:

To made it work as I said in my post:

$request = $GLOBALS['_' . $_SERVER['REQUEST_METHOD']];

Why?

Because $_POST and $_GET are global variables and need to accessed as such. Inside functions/classes you would usually do something like:

global $_POST;

before using.

You could also use the original code outside of a function or class.

Better way in this case?

My intention with this was to support multiple request methods. I don't thing that this would work for PUT/PATCH/DELETE etc. I would advise instead you use:

$requestdata = fopen("php://input", "r");

See: http://php.net/manual/en/features.file-upload.put-method.php

This may not work for url parameters only request body. Not sure. (If this is the case then for get REQUESTS you'd want to use $_GET

相关阅读:
Top