如何根据给定的代码遍历类的每个实例:
class Project {
// Constructor
public function __construct($projectTitle, $projectSummary, $projectTools) {
$this->projectTitle = $projectTitle;
$this->projectSummary = $projectSummary;
$this->projectTools = $projectTools;
}
我创建了以下公共函数:
public function displayProjectCard() {
echo '<div class="card mt-4 w-75" >
<div class="card-body">
<h5 class="card-title">' . $this->projectTitle . '</h5>
<p class="card-text">' . $this->projectSummary . '</p>
<p class="tools">' . $this->projectTools . '</p>
</div>
</div>';
}
...但是我不确定如何-或是否有可能-遍历每个类实例,以便每个“ projectCard”都显示在其自己的Bootstrap卡中。
实例的创建方式如下:
$project1 = new Project(
"Project Title",
"This is where you'll write a description of your project and related features.",
"Tools",
);
目标是使结果看起来像这样:
答案 0 :(得分:1)
根据您的代码,我将采用以下方式:
// instantiate projects array like this
$projects = array(
new Project("Title1", "Summary", "Tools"),
new Project("Title2", "Summary", "Tools"),
new Project("Title3", "Summary", "Tools"),
new Project("Title3", "Summary", "Tools"),
);
// then iterate each $projects and then call the displayProjectCard()
foreach ($projects as $project) {
$project->displayProjectCard();
}