douren4075 2011-02-05 17:30
浏览 42

将字符串转换为变量名称

I am working on a function that takes a string as an argument, which I need to use to get the value of a variable of the same name.

For example

If the string $foo = "$_POST['email']"; is passed I need to retrieve the value of $_POST['email'] and store it as $example, so that $_POST['email'] == $example would return true. There is no feasable way of passing the value directly to function (the variable has to be dynamic to make the function worthwhile).

I did think of using variable variables but they don't work with super globals which will be the primary source of the values I need.

Basically is there a way to get the value of a variable (usually in a superglobal array) with the needed variable as a string?

Let me know if more detail is needed.

Thanks

  • 写回答

2条回答 默认 最新

  • dongxinjun3944 2011-02-05 17:34
    关注

    Variable variables would be the answer, but if you're after fetching values from $_POST array, why not pass just a key to a function?

    Note: ths function is provided just for example, my actual recommendation is below.

    function fetchFromPost($key) {
      if(isset($_POST[$key]) {
        return $_POST[$key];
      } else {
        return null; //or do whatever you want to do in case key is not found
      }
    }
    

    In fact filter_input(), which allows you to chose an input array, a key and a sanitaion filter to be used, is already there for you

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号