drlnsli18864734 2010-11-15 02:08
浏览 238
已采纳

你能在PHP中获得一个变量名作为字符串吗? (你应该吗?)

Say you have several large arrays of variables (which generally are strings), and you want to change how they are displayed on certain pages – for example by concatenating each of them with $prefix and $suffix:

$arr = array($foo, $bar, $baz)

$foo_display = $prefix . $foo . $suffix
$bar_display = $prefix . $bar . $suffix
$baz_display = $prefix . $baz . $suffix

How would you avoid having to make all these assignments manually? I originally assumed there would be some function which would return a variable's name as a string (call it "varname()"), in which case the code might look like this:

foreach ($arr as &$value) {
    ${varname($value)."_display"} = $prefix . $value . $suffix
}

But I haven't been able to find such a function, and people in this similar thread seemed to think the entire concept was suspect.

PS: I'm new to programming, sorry if this is a dumb question :)

  • 写回答

3条回答 默认 最新

  • dongyupen6269 2010-11-15 02:36
    关注

    There are multiple problems with what you want to do. For example, the name of the variable is not accessible. The code $arr = array($foo, $bar, $baz) creates an array with the values of the $foo, etc. If you then changed the value of $foo, the value of $arr[0] is still the old value of $foo, so it's not even clear what it would mean to have access to the variables name.

    Even if it were easy to do, I would consider it very poor practise, simply because you'd need to know by introspection what the correct variable names would be.

    Of course, this is all easily solved if you had an associative array. For example:

    $arr = array('Foo' => $foo, 'Bar' => $bar, 'Baz' => $baz)
    

    This could easily be altered to produce what you want. For example:

    $display = array();
    foreach($arr as $key => $value) 
       $display[$key] = $prefix . $value . $suffix;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站