简体   繁体   English

PHP:使用变量访问对象属性

[英]PHP: Accessing an object property with a variable

Let's assume I have an array of object properties I'd like to access: 假设我有一个要访问的对象属性数组:

$properties = array('foo', 'bar');

I'd like to loop through the object and access these properties dynamically (specifically, I'm trying to dynamically handle missing JSON elements based on an array of expected elements): 我想遍历该对象并动态访问这些属性(特别是,我正在尝试根据期望的元素数组动态处理缺少的JSON元素):

foreach ($data as $item) {
    foreach ($properties as $property) {
        if (empty($item->{$property})) {
            // Do something
        }
    }
}

Each $item in $data should have the properties 'foo' and 'bar'. $ data中的每个$ item应该具有属性'foo'和'bar'。 I'm handling the cases where 'foo' or 'bar' doesn't exist. 我正在处理“ foo”或“ bar”不存在的情况。

I'm trying to get the loop (in line 3) to access $item->{'foo'} and $item->{'bar'}, but it's not working. 我正在尝试使循环(第3行)访问$ item-> {'foo'}和$ item-> {'bar'},但是它不起作用。

Any idea why? 知道为什么吗? I'm fairly certain it's a matter of syntax, but obviously I haven't been able to figure this out! 我相当确定这是语法问题,但显然我无法弄清楚!

Thanks! 谢谢!

Could you not use property_exists($item, $property) . 您能不能使用property_exists($item, $property)

foreach ($data as $item) {
    foreach ($properties as $property) {
        if ( property_exists($item, $property) ) {
            // Do something
        }
    }
}

If what you're doing involves modifying the original set of items, keep in mind that foreach operates on a copy of the original array. 如果您要执行的操作涉及修改原始项目集,请记住, foreach在原始数组的副本上进行操作。 If you want to modify things in the original array, you'll need to use something like foreach($arr as $k => $v) syntax, then modify $arr[$k] . 如果要修改原始数组中的内容,则需要使用诸如foreach($arr as $k => $v)语法,然后修改$arr[$k]

I figured it out... 我想到了...

I think I was working on the wrong portion of the object. 我认为我正在处理对象的错误部分。

Thanks for the informative answers! 感谢您提供的有用信息!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM