PHP如何使用字符串作为超全局

发布于 2024-07-17 11:45:47 字数 790 浏览 5 评论 0原文

我正在构建一个小型抽象类,它应该使某些任务变得更容易。

例如: $var = class::get('id'); 会运行检查$_GET中是否有指针id,根据参数返回字符串或数组。 这也适用于发布和请求,甚至更多。

我正在以所有超全局函数都有功能的方式来做这件事。 我以 get 为例:

get 函数获取一个指针作为参数,它调用 fetchdata 函数并使用指针和“$_GET”作为参数。

fetchdata 应该只是盲目地使用它作为超全局的字符串,并用其他参数指向它。 然后检查它是否存在,并返回 value 或 false 来获取函数,该函数将 value/false 返回给调用者。

唯一的问题是,当您不知道字符串是什么时,如何让字符串作为超全局字符串工作。 我之前使用一个检查参数的开关来完成此操作,如果它是“get”,它将 $_GET 设置为另一个变量的值。 但是我不想那样做,我希望可以轻松添加更多功能,而不必接触 fetchdata。

我尝试了 $method = eval($method),但没有成功。 ($method = "$_GET"),有什么建议吗?

编辑:抱歉,如果我说得不够清楚。 我有一个带有字符串值“$_GET”的变量 X,如何才能使 X 从字符串中描述的源获取值?

所以简单地说,

如果 X 的值为“$_GET”,则 $X = $_GET

如果 X 的值为“$_POST”,则 $X = $_POST

我只是不知道 X 的值是什么,但它需要使用以下命令从超全局获取数据名称与其值相同。

I'm building a small abstract class that's supposed to make certain tasks easier.

For example:
$var = class::get('id');
would run check if there's pointer id in the $_GET, returning a string or array according to parameters. This should also work for post and request and maby more.

I'm doing it in the way there's function for all the superglobals. I'm using get as example:

get function gets a pointer as parameter, it calls fetchdata function and uses the pointer and "$_GET" as the parameters.

fetchdata is supposed to just blindly use the string it got as superglobal and point to it with the other param. Then check if it exists there and return either the value or false to get function, that returns the value/false to caller.

Only problem is to get the string work as superglobal when you don't know what it is. I did this before with a switch that checked the param and in case it was "get", it set $_GET to value of another variable. However I don't want to do it like that, I want it to be easy to add more functions without having to touch the fetchdata.

I tried $method = eval($method), but it didn't work. ($method = "$_GET"), any suggestions?

EDIT: Sorry if I didn't put it clear enough. I have a variable X with string value "$_GET", how can I make it so X gets values from the source described in the string?

So simply it's

$X = $_GET if X has value "$_GET"

$X = $_POST if X has value "$_POST"

I just don't know what value X has, but it needs to get data from superglobal with the same name than its value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

撩动你心 2024-07-24 11:45:47

根据手册中的此页面

注意:变量变量

超全局变量不能用作函数或类方法内的变量。

这意味着您不能在函数或方法中执行此操作(您可以使用其他变量执行此操作):

$var = '_GET';
${$var}[$key]

而不是将字符串传递给fetchdata(),你不能传递 $_GET 本身吗? 我认为 PHP 不会复制变量,除非你修改它(“写时复制”),所以这不应该不必要地使用内存。

否则只有九个超全局变量,因此您所建议的 switch-case 并不是不合理的。

如果确实需要,您可以使用 eval() 来完成此操作,例如:

eval('return $_GET;');

我认为这是不必要的,而且是一个坏主意; 它很慢,您需要非常小心,不要让不受信任的字符串靠近它。

According to this page in the manual:

Note: Variable variables

Superglobals cannot be used as variable variables inside functions or class methods.

This means you can't do this inside a function or method (which you would be able to do with other variables) :

$var = '_GET';
${$var}[$key]

Instead of passing a string to fetchdata(), could you not pass $_GET itself? I think PHP will not copy a variable unless you modify it ('copy on write'), so this shouldn't use memory unnecessarily.

Otherwise there are only nine superglobals, so a switch-case as you have suggested isn't unreasonable.

You could do this with eval() if you really had to, something like:

eval('return $_GET;');

I think that would be unnecessary and a bad idea though; it is slow and you need to be extremely careful about letting untrusted strings anywhere near it.

眼中杀气 2024-07-24 11:45:47

不要使用评估。 就用参考吧。

//test value for cli
$_GET['test'] = 'test';

/**
 * @link http://php.net/manual/en/filter.constants.php reuse the filter constants
 */
function superglobalValue($key, $input = null) {
    if ($input === INPUT_POST)
        $X = &$_POST;
    else
        $X = &$_GET;
    return (isset($X[$key]) ? $X[$key] : false);    
}

function getArrayValue(&$array, $key) {
    return (array_key_exists($key, $array) ? $array[$key] : false); 
}

//test dump
var_dump(
    superglobalValue('test', INPUT_GET),
    superglobalValue('test', INPUT_POST),
    getArrayValue($_GET, 'test'),
    getArrayValue($_POST, 'test')
);

$_GET、$_POST 和 $_REQUEST 默认没有任何空值,只有字符串或数组。 所以我在那里使用 isset 而不是 array_key_exists。

参数顺序:如果可以的话,我总是将必需的参数放在可选参数之前,并将数据对象放在操作/主观参数之前。 这就是为什么 key 是 superglobalValue 的第一个参数和 getArrayValue 的第二个参数。

Don't use eval. Just use reference.

//test value for cli
$_GET['test'] = 'test';

/**
 * @link http://php.net/manual/en/filter.constants.php reuse the filter constants
 */
function superglobalValue($key, $input = null) {
    if ($input === INPUT_POST)
        $X = &$_POST;
    else
        $X = &$_GET;
    return (isset($X[$key]) ? $X[$key] : false);    
}

function getArrayValue(&$array, $key) {
    return (array_key_exists($key, $array) ? $array[$key] : false); 
}

//test dump
var_dump(
    superglobalValue('test', INPUT_GET),
    superglobalValue('test', INPUT_POST),
    getArrayValue($_GET, 'test'),
    getArrayValue($_POST, 'test')
);

$_GET, $_POST and $_REQUEST dont have any null values by default, only string or array. So I used isset there instead of array_key_exists.

Param order: I always put required params before optional when I can, and the data objects before the manipulation/subjective params. Thats why key is first param for superglobalValue and second param for getArrayValue.

沦落红尘 2024-07-24 11:45:47

我不太确定你想要实现什么,但你可以看看

class example{
 protected static $supers = array('GET', 'POST', 'SERVER', 'COOKIE');
 public static function __callStatic($functionName, $arguments){
  $index = arguments[0];
  $desiredSuper = strtoupper($functionName);
  if(in_array($desiredSuper, self::$supers)){
   doStuff ( $_{$desiredSuper}[$index] );
  }
  else{
    throw new Exception("$desiredSupper is not an allowed superGlobal");
  }
 }
} 

你可以执行的 __callStatic 魔术方法:

 example::get('id'); //wo do stuff to $_GET['id']
 example::server('REQUEST_METHOD'); //Will do stuff to $_SERVER['REQUEST_METHOD']
 example::foo('bar'); //throws Exception: 'FOO is not an allowed superGlobal'

Php 魔术方法手册: http://ca.php.net/manual/en/language.oop5.overloading.php# language.oop5.overloading.methods

编辑
我刚刚注意到您的编辑,您可以尝试:

 $X  = {$X};

I'm not quite sure what you're trying to achieve, but you could have a look at the __callStatic magic method

class example{
 protected static $supers = array('GET', 'POST', 'SERVER', 'COOKIE');
 public static function __callStatic($functionName, $arguments){
  $index = arguments[0];
  $desiredSuper = strtoupper($functionName);
  if(in_array($desiredSuper, self::$supers)){
   doStuff ( $_{$desiredSuper}[$index] );
  }
  else{
    throw new Exception("$desiredSupper is not an allowed superGlobal");
  }
 }
} 

you could then do:

 example::get('id'); //wo do stuff to $_GET['id']
 example::server('REQUEST_METHOD'); //Will do stuff to $_SERVER['REQUEST_METHOD']
 example::foo('bar'); //throws Exception: 'FOO is not an allowed superGlobal'

Php manual on magic methods: http://ca.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods

Edit
I just noticed your edit, you could try:

 $X  = {$X};
酷到爆炸 2024-07-24 11:45:47

您可以使用 $_REQUEST["var"] 代替 $_GET["var"] 或 $_POST["var"]。

更复杂的方法是测试变量是否存在于 GET 数组中,如果不存在则测试其 POST 数组。 如果它执行了 GET。

$var = null;
if (isset($_GET["varname"]))
{
  $var = $_GET["varname"];
}
else
{
  $var = $_POST["varname"];
}

You can use $_REQUEST["var"] instead of $_GET["var"] or $_POST["var"].

A more complicated way would be to test if the variable exists in the GET array, if it doesnt then its POST. If it does its GET.

$var = null;
if (isset($_GET["varname"]))
{
  $var = $_GET["varname"];
}
else
{
  $var = $_POST["varname"];
}
潦草背影 2024-07-24 11:45:47

如果您希望某个变量可以全局访问,可以将其添加到 $GLOBALS 数组中。

$GLOBALS['test']='test';

现在您可以在任何地方获取 $GLOBALS['test']

If you want a variable to be accessible globally, you can add it tot he $GLOBALS array.

$GLOBALS['test']='test';

Now you can fetch $GLOBALS['test'] anywhere.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文