变量名作为变量 [英] Variable name as variable

查看:30
本文介绍了变量名作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用变量作为变量名的问题.我有一个以数据库字段名作为键和对象属性作为值的数组像这样:

I have a question about using variables as variablename. I have an array with database fieldnames as key and object properties as values like this:

$properties = array("userid" => "user['userid']", "city" => "hometown");

foreach ($properties as $field => $property ) { 
  $value1 = $db->$field;
  $value2 = $obj->$property;
}

这适用于财产家乡,但不适用于财产用户 ['userid'].寻址属性变量的正确方法是什么?
我还尝试了几种方法,例如:${property} 或 {$property},但还没有运气.

This works for the property hometown but doesn't work voor de property user['userid']. What is the correct way to adress the property variable?
I also tried several things like: ${property} or {$property} but without luck yet.

感谢所有的回复!现在我将保留我原来的解决方案,我想知道是否有办法,我对 eval 版本没有主要问题,会记住它!

edit: Thanks for all the responses! For now I'll stay with my original solution, I was wondering if there was a way, I don't have principal problems with the eval version, will keep it in mind!

 foreach ($fields as $field => $property ) {
        switch ($field) {
            case "userid":
                $newvalue = $this->user['userid'];
                $oldvalue = $original->user['userid'];
                break;
            // more cases ...
            default:
                $newvalue = $this->{$property};
                $oldvalue = $original->($property};
        } 
        ....

推荐答案

好的,所以我决定评论这个问题.Kai(无意冒犯:) 为您提供了一个不使用 eval 的解决方案,但代价是增加了 12 行左右的代码,这无疑使代码变得更慢、更复杂.所以我自己认为在这种情况下,使用 eval() 调用是合理的.然而,那可能只是我(我非常看重清晰和简短的代码).

OK, so I decided to comment on this problem. Kai (no offence :) provided you a solution which doesn't use eval, but at the cost of additional 12 or so lines of code, making the code no doubt slower and more complex. So I myself think that in this case, it is justified to use eval() call. Hovewer, that could be just me (I value clear and short code a lot).

但要注意,如果输入来自外部来源,那么您应该对其进行过滤.

But beware, if input is coming from external sources, then you should filter it.

$properties = array("userid" => "user['userid']", "city" => "hometown");

foreach ($properties as $field => $property ) { 
  $value1 = $db->$field;
  eval("\$value2=\$obj->$property;");
}

这篇关于变量名作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆