Docs/PHP/Include & Require

Include & Require

Perbedaan

  • include — warning jika file tidak ada (lanjut eksekusi)
  • require — fatal error jika file tidak ada (stop)
  • include_once / require_once — hanya include 1x

Use Cases

  • Header/footer template
  • Database connection
  • Helper functions
  • Config files
index.php
Try It →
<?php
// === header.php ===
// <header><h1>My Site</h1><nav>...</nav></header>

// === footer.php ===
// <footer>&copy; 2024</footer>

// === db.php ===
// $pdo = new PDO(...);

// === page.php ===
echo "// Typical PHP page structure:

";

echo '<?php
';
echo 'require_once "config.php";    // config (fatal if missing)
';
echo 'require_once "db.php";        // database
';
echo 'include "helpers.php";        // optional helpers
';
echo 'include "header.php";         // HTML header
';
echo '?>

';
echo '<main>Page content here</main>

';
echo '<?php include "footer.php"; ?>

';

echo "// require_once prevents loading same file twice
";
echo "// Great for class autoloading";
?>