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();
}
Sometimes it is worth writing a simple test, saving to a separate file, and then running script through the PHP interpreter from the command-line. When debugging complicated code, it is easy to bark up the wrong tree. If you are feeling ambitious, you can take it one step further and explore writing unit tests using PHPUnit.
<?php
$statuses = array(
'test1',
'test2',
'test3',
'test4',
'test5',
'test6',
'test7',
'test8',
'test9',
'test10',
'test11'
);
class StatusMessage {
private $status;
function __construct($status) {
$this->status = $status;
}
function getInteractions() {
return $this->status . " interactions";
}
function getMessage() {
return $this->status . " messages";
}
}
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);
//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() . "\n";
}
//This loop doesn't work. Throws the error mentioned above
for ($i = 0; $i < 10; $i++) {
echo '[' . $statObjs[$i]->getInteractions() . '] ' . $statObjs[$i]->getMessage() . "\n";
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With