Is using classes the best approach for building tables with different content but consistent appearance in PHP?
Using classes is a good approach for building tables with different content but consistent appearance in PHP. By defining a class for the table structure and styling, you can easily reuse the same design across multiple tables with varying content. This approach promotes code reusability, maintainability, and consistency in the appearance of your tables.
<?php
class Table {
private $data;
public function __construct($data) {
$this->data = $data;
}
public function render() {
echo '<table>';
foreach ($this->data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
// Example usage
$tableData = [
['John', 'Doe', 'john.doe@example.com'],
['Jane', 'Smith', 'jane.smith@example.com'],
];
$table = new Table($tableData);
$table->render();
?>