简体   繁体   English

php $_POST 使用 $$ 调用

[英]php $_POST using $$ call

I'm aware that the following piece of code is possible in php:我知道在 php 中可以使用以下代码:

$dog = 'Woof!';
$cat = 'Miauw!';
$animal = 'dog';
var_dump($$animal);

Output: 'Woof!' Output:“哇!”

Of course this is a simplified example of my actual code, nonetheless you get the idea.当然,这是我实际代码的简化示例,但是您明白了。 Now I can't seem to get the $_POST variable to act the same way.现在我似乎无法让$_POST变量以相同的方式运行。

Example:例子:

$method = '_POST';
$$method['password'] = array();
// In the end i would want this piece of code above to do what i typed below
$_POST['password'] = array();

Output: 'Notice: Undefined variable: _POST' Output:'注意:未定义变量:_POST'

So does this mean it is not possible to call $_POST this way or am I doing it the wrong way?那么这是否意味着无法以这种方式调用 $_POST 还是我做错了?

From php manual :来自php 手册

Note: Variable variables Superglobals cannot be used as variable variables inside functions or class methods.注意:变量变量 Superglobals 不能用作函数或 class 方法内部的变量变量。

As outlined by the other answers, not even the superglobals are real globals in PHP.正如其他答案所述,即使是超全局变量也不是 PHP 中的真正全局变量。 They need to be specifically imported into the local scope dict to be accessible with variable variables.它们需要专门导入到本地 scope 字典中,才能通过变量变量进行访问。

If you really only want to access $_POST and $_GET or $_REQUEST, then the explicit syntax would be however:如果您真的只想访问 $_POST 和 $_GET 或 $_REQUEST,那么显式语法将是:

$GLOBALS[$method]['password'] = array();
$$method['password'] = array();

is evaluated as:被评估为:

${$method['password']} = array();

PS: You might be better off not doing this. PS:你最好不要这样做。 Variable variables are confusing and considered a bit of a bad practice.变量变量令人困惑,被认为是一种不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM