PHP - 通过变量获取对象属性 [英] PHP - Get object properties by variable

查看:159
本文介绍了PHP - 通过变量获取对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有很多属性的对象.一些属性的名称以相同的文本字符串开头(在我的示例中为bullet"),后跟一个整数.

I have an object with lots of properties. Some of the properties have their names start with the same string of text (in my example to come "bullet"), followed by an integer.

我可以按如下方式获取属性值:

I can fetch the property values as follows:

echo $objectName->bullet1;
echo $objectName->bullet2;
echo $objectName->bullet3;

等等.

我正在尝试编写一个 for 循环来获取其中的前 20 个,目前看起来有点像:

I'm trying to write a for loop to get the first 20 of these, and at the moment it looks a bit like:

for ($i = 1; $i <= 20; $i++){
 if ($objectName->bullet$i){
  echo $objectName->bullet$i;
 }
}

但这不起作用.我知道我可以写一些类似的东西

But this isn't working. I know I could write something like

$bulletsArray[1] = $objectName->bullet1;
$bulletsArray[2] = $objectName->bullet2;
$bulletsArray[3] = $objectName->bullet3;

一直到 20,然后在上面放一个 for 循环,但我相信一定有更简洁的方法.有人能指出我正确的方向吗?

all the way through to 20, then put a for loop on that, but I'm sure there must be a cleaner way. Can someone point me in the right direction?

推荐答案

您可以这样做:

for ($i = 1; $i <= 20; $i++){
    $propertyName = "bullet$i";
    if ($objectName->$propertyName){
        echo $info->$propertyName;
    }
}

虽然我认为使用数组而不是对象会是更好的解决方案.

Though I think using an array instead of the object would be a better solution.

这篇关于PHP - 通过变量获取对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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