I'm coming from Java and just continued learning PHP. So, I'm trying to follow some similar patterns in that I use in Java to get values from database.
There's just one problem that I don't know how to solve. I can't find a way to properly store objects (which has its values / attributes set using the set()
methods) to an Array
or ArrayList
. I think that PHP don't have ArrayList
or List
or HashMaps
But anyways, I basically want to know the correct idiom,syntax or way to store objects which I instantiated by keyword new
to the common type of PHP collection where I can easily retrieve objects from later by using get()
methods.
function getAllAnnouncementByMostRecent()
{
try{
$SQL = "CALL getAllAnnouncementByMostRecent()";
$spGetAnnouncements = $this->connection->prepare($SQL);
$spGetAnnouncements->execute();
$resultSet = $spGetAnnouncements->fetchAll(PDO::FETCH_ASSOC);
$announcementList = [];
foreach($resultSet as $row){
$announcement = new Announcement();
$announcement->setId($row['announcement_id']);
$announcement->setTitle($row['announcement_title']);
$announcement->setContent($row['announcement_content']);
$announcement->setDateAdded($row['date_added']);
$announcementList[] = $announcement;
}
return $announcementList;
}catch (PDOException $e){
die($e->getMessage());
}
}
So I tried to retrieve data from it but got an error stating that there's
Warning: Invalid argument supplied for foreach()
<div class="bottom-menu-content-container">
<?php
$announcementDaoImpl = new AnnouncementDaoImpl($pdo);
$announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
foreach($announcementList as $key => $value)
{
echo "<label>". $value. "</label>";
}
?>
</div>
I tried to var_dump()
the contents of $announcementList
and I get the ff:
array(1) { [0]=> object(Announcement)#4 (4) { ["id":"Announcement":private]=> int(1) ["title":"Announcement":private]=> string(23) "Test Announcement Title" ["content":"Announcement":private]=> string(25) "Test Announcement Content" ["dateAdded":"Announcement":private]=> string(19) "2018-04-22 16:12:06" } }
I'd appreciate any help.
Thank you.
--- EDIT (SOLVED) ---
Thanks everyone for your suggestions and help. It was solved by simply accessing the get()
method of the object as suggested by William Perron and ADyson
<div class="bottom-menu-content-container">
<?php
$announcementDaoImpl = new AnnouncementDaoImpl($pdo);
$announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
foreach($announcementList as $key => $value)
{
echo $value->getTitle(); //no need to cast
}
?>
</div>
To those who might see this question during search who might also be coming from a different programming language, the only thing that I was confused was the casting of objects.
Thanks.
--- end of edit ----