[英]access a property via string with array in php?
I have a big list of properties that I need to map between two objects, and in one, the value that I need to map is buried inside an array. 我有一个很大的属性列表,需要在两个对象之间进行映射,其中一个属性是将需要映射的值掩埋在一个数组中。 I'm hoping to avoid hard-coding the property names in the code. 我希望避免在代码中对属性名称进行硬编码。
If I have a class like this: 如果我有这样的课程:
class Product {
public $colors, $sizes;
}
I can access the properties like this: 我可以这样访问属性:
$props = array('colors', 'sizes');
foreach ($props as $p) {
$this->$p = $other_object->$p;
}
As far as I can tell, if each of the properties on the left are an array, I can't do this: 据我所知,如果左侧的每个属性都是一个数组,我将无法执行此操作:
foreach ($props as $p) {
$this->$p[0]['value'] = $other_object->$p;
}
Is that correct, or am I missing some clever way around this? 是正确的,还是我错过了一些巧妙的方法?
(This is in drupal, but I don't really think that matters.) (这在drupal中,但我并不认为这很重要。)
I believe you can wrap it in curly braces {}
: 我相信您可以将其用大括号{}
包裹起来:
foreach ($props as $p) {
$this->{$p}[0]['value'] = $other_object->$p;
}
Edit: 编辑:
Okay. 好的。 Now my brain turned on. 现在我的大脑打开了。 Sorry for the confusing edits. 抱歉,造成混乱的编辑。
也尝试一下:
$props = get_object_vars($this);
foreach ($props as $p) {
$this->{$p}[0]['value'] = $other_object->{$p};
}
It's called variable, variables . 这就是所谓的变量 。
I don't understand your problem. 我不明白你的问题。 This works: 这有效:
class Test {
public $prop = "prov value";
}
$arr = array(array("prop"));
$test = new Test();
$test->$arr[0][0] = "new prop value";
var_dump($test);
result: 结果:
object(Test)#1 (1) { ["prop"]=> string(14) "new prop value" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.