How do I create a table in PHP filled with new objects
Get the solution ↓↓↓I'm looking to build an HTML table within myoutputAsTable()
method. However, I have tried many ways with no correct result. Can some one help with the HTML/PHP code needed or some pointers to what it is I need to build a table displaying the new book objects as I'm new to PHP and still learning.
<?php
class Book {
public $author; //property
public $title; //property
public $publisher; //property
public $year; //property
# constructor for each new book
public function __construct($author, $title, $publisher, $year) {
$this->author = $author;
$this->title = $title;
$this->publisher = $publisher;
$this->year = $year;
}
# method to display new book objects in a table
public function outputAsTable($book) {
//build a table and display new book objects
}
}
# an array of books
$books = array(
new Book("author1", "title1", "publisher1", "year1"),
new Book("author2", "title2", "publisher2", "year2"),
new Book("author3", "title3", "publisher3", "year3"),
new Book("author4", "title4", "publisher4", "year4"),
new Book("author5", "title5", "publisher5", "year5")
);
foreach($books as $book) {
echo outputAsTable($book);
}
?>
Answer
Solution:
There are a few things to do:
Replace the foreach with: (the foreach will move into the output function)
Books::outputAsTable($books);
Change the class function definition to be static, and the param:
public static function outputAsTable($books)
Then in
outputAsTable
function:public static function outputAsTable($books) { echo '<table> <tr> <th>Author</th><th>Title</th><th>Publisher</th><th>Year</th> </tr>'; foreach($books as $book) { echo "<tr><td>{$book->author}</td> <td>{$book->title}</td> <td>{$book->publisher}</td> <td>{$book->year}</td></tr>"; } echo '</table>'; }
The reason I used thestatic
route is because you already have an array ofBook
objects. An instance ofBook
would be needed to use theoutputAsTable
function without it being static. With the function being static, you can pass the$books
array to use within the function as needed.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: zsh: command not found: php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.