0

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.

3
  • Why do you use ninja code? Commented Feb 16, 2015 at 10:32
  • 1
    possible duplicate of Superglobals can't be accessed via variable variables in a function? Commented Feb 16, 2015 at 10:43
  • @VeeeneX I was using this code to support multiple request methods. Primarily GET and POST, I don't know that this would work for PATCH/PUT/DELETE, etc. Note my recent answer which probably is a better way to do it Commented Apr 4, 2016 at 19:04

2 Answers 2

0

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?

Sign up to request clarification or add additional context in comments.

1 Comment

@deltababel The reason I was doing this magically was so the server worked for multiple request methods. Ex. get and post
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.