How can one create a dynamic page inclusion system in PHP without relying on switch or else statements?
When creating a dynamic page inclusion system in PHP, using switch or else statements can become cumbersome and hard to maintain as the number of pages increases. One alternative approach is to use an array to map page names to their corresponding file paths. This allows for a more scalable and flexible solution without the need for multiple conditional statements.
<?php
// Define an array mapping page names to file paths
$pages = [
'home' => 'pages/home.php',
'about' => 'pages/about.php',
'contact' => 'pages/contact.php'
];
// Check if the requested page exists in the array, if not, include a default page
$page = isset($_GET['page']) && isset($pages[$_GET['page']]) ? $_GET['page'] : 'home';
// Include the corresponding page file
include $pages[$page];
?>
Related Questions
- How can PHP be utilized to mark forum posts as new for users and then as old once they have been viewed?
- How can PHP developers effectively troubleshoot issues related to array manipulation and function parameters like setFiles?
- How can I avoid using create_function for creating custom functions in PHP?