dongyou8368 2011-04-13 22:23
浏览 70

PHP - 可以调用存储在数组中的对象的成员函数吗?

I'm new to PHP and spent some time searching for a similar question, but none seemed to quite answer it for me.

I have an array of Objects (a class I created called StatusMessage) and I want to access a member function of each object in the array. I am able to do this using a foreach loop, but I only need to access the first 10 objects (they are sorted) so I am trying to use a for loop. When I make the member function calls, I get a fatal error about not being able to call member functions on non-objects. Do the StatusMessage objects in $statObjs need to be cast or something?

Any suggestions?

function collectStatuses($statusesAPI){

    $statusObjects = Array();   
    foreach($statusesAPI as $status)
    {
      //StatusMessage is a class I created
    array_push($statusObjects, new StatusMessage($status));             
    }           
    return $statusObjects;
}

//$statutuses[data] was populated further up
$statObjs = collectStatuses($statuses[data]);

//This loop works, but prints all StatusMessage objects in $statObjs 
foreach ($statObjs as $value) {
  //getInteractions() and getMessages() are both member functions of the StatusMessage class I created.
  echo '[' . $value->getInteractions() . '] ' .  $value->getMessage();
}

//This loop doesn't work. Throws the error mentioned above
for ($i = 0; $i < 10; $i++) {

  echo '[' . $statObjs[$i]->getInteractions() . '] ' .  $statObjs[$i]->getMessage();
}
  • 写回答

5条回答 默认 最新

  • dongyi1921 2011-04-13 22:31
    关注

    Is that the actual code? There are a couple of mistakes.

    Three of the 'i' variables in that last loop are missing dollar signs.

    $i<10
    $statObjs[$i]->
    $statObjs[$i]->
    

    You are incrementing $j, when you want to increment $i ($i++)

    Also, if there aren't 10 status messages, you may want to count $i < min(10, $statObjs.length)

    Hope this helps,

    Chris

    评论

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了