PHP: Constants and Includes

Constants are values that never change. Database passwords, API keys, site names — any data that stays the same throughout your program's execution should be a constant, not a variable. This lesson also teaches you how to split your code across multiple files with include and require.

1. define() vs const

PHP gives you two ways to declare constants:

PHP
<?php
// define() — declared at runtime (can be used anywhere)
define("SITE_NAME", "My Blog");
define("MAX_UPLOAD_SIZE", 5 * 1024 * 1024);  // 5MB
define("DB_HOST", "localhost");

// const — declared at compile time (global scope only)
const APP_VERSION = "2.0.0";
const PI = 3.14159;

echo SITE_NAME;      // My Blog (note: no $ prefix)
echo APP_VERSION;    // 2.0.0
?>
define() const
Where Anywhere (inside functions/conditions) Global scope only
Timing Runtime Compile time (slightly faster)
Arrays ✅ PHP 7+ ✅ PHP 5.6+
Expressions ❌ Simple values only
Best for Config, conditional definitions Class constants
💡 Tip: In most cases, prefer const — it's slightly faster and reads more clearly. Only use define() when you need a dynamically computed value or need to define a constant inside a function or conditional block.

(1) Naming Convention

Constants use ALL_CAPS with underscores (SCREAMING_SNAKE_CASE):

PHP
<?php
const MAX_LOGIN_ATTEMPTS = 5;
const DEFAULT_LANGUAGE = "en-US";
const API_BASE_URL = "https://api.example.com/v1";
?>

(2) Checking If a Constant Exists

PHP
<?php
if (!defined("SITE_NAME")) {
    define("SITE_NAME", "Default Site Name");
}
// defined() checks whether a constant is already set
?>

2. Magic Constants

PHP provides a set of "magic constants" whose values change automatically depending on where they're used:

PHP
<?php
// Assume the file path is: C:\xampp\htdocs\myphp\demo.php

echo __LINE__;       // Current line number: 7
echo __FILE__;       // Full file path: C:\xampp\htdocs\myphp\demo.php
echo __DIR__;        // Directory of the file: C:\xampp\htdocs\myphp
echo __FUNCTION__;   // Current function name (inside a function)
echo __CLASS__;      // Current class name (inside a class)
echo __METHOD__;     // Current method name (inside a method)
echo __NAMESPACE__;  // Current namespace
?>

▶ サンプル: Reliable Paths with __DIR__

PHP
<?php
// ❌ Fragile relative path
$config = include "config.php";

// ✅ Always resolves to the correct absolute path
$config = include __DIR__ . "/config.php";
$avatar = __DIR__ . "/uploads/avatars/" . $userId . ".jpg";
?>
▶ 試してみよう
💡 Tip: __DIR__ is the magic constant you'll use most in everyday development. Always use __DIR__ to build paths in your includes — it guarantees the file is found no matter which directory the script is called from.


3. include vs require

Split your code across files and pull them in with include or require:

PHP
<?php
// config.php
const DB_HOST = "localhost";
const DB_NAME = "myapp";
?>
PHP
<?php
// index.php
require __DIR__ . "/config.php";

echo "Database host: " . DB_HOST;  // Constants are now available
?>
include require
File not found ⚠️ Warning, script continues 🔴 Fatal Error, script stops
Reuse Can be included multiple times Can be included multiple times
Best for Optional content Essential config, function libraries
💡 Tip: Here's a simple rule — use require by default. If a config file or function library is missing, your script should stop immediately rather than limp along with broken logic. Reserve include for truly optional pieces like ad banners or analytics snippets.

(1) include_once and require_once

Prevent the same file from being loaded more than once:

PHP
<?php
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/config.php";  // Second call does nothing
?>
💡 Tip: Use require_once for files that define functions or classes (redefining them would cause a fatal error). Use plain require for HTML template fragments that you might include multiple times intentionally.


4. Predefined Constants

PHP ships with a number of built-in global constants:

PHP
<?php
echo PHP_VERSION;        // 8.2.7
echo PHP_INT_MAX;        // 9223372036854775807 (64-bit)
echo PHP_INT_MIN;        // -9223372036854775808
echo PHP_FLOAT_MAX;      // 1.7976931348623E+308
echo PHP_EOL;            // Line break (\n or \r\n depending on OS)
echo DIRECTORY_SEPARATOR; // \ (Windows) or / (Unix)
echo PATH_SEPARATOR;      // ; (Windows) or : (Unix)
?>

These are especially handy for writing cross-platform code.


5. Modular Development in Practice

Organize your site into multiple files glued together with require:

TEXT 📖 参照専用
myphp/
├── config.php      ← Database config, constants
├── functions.php   ← Shared functions
├── header.php      ← Page header HTML
├── footer.php      ← Page footer HTML
├── index.php       ← Home page
└── about.php       ← About page

▶ サンプル: A Modular Page

PHP
<?php
// header.php
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= $pageTitle ?? "My Website" ?></title>
</head>
<body>
<header>
    <h1><?= SITE_NAME ?></h1>
    <nav>
        <a href="/">Home</a>
        <a href="about.php">About</a>
    </nav>
</header>
<main>
▶ 試してみよう
PHP
<?php
// footer.php
?>
</main>
<footer>
    <p>&copy; <?= date("Y") ?> <?= SITE_NAME ?></p>
</footer>
</body>
</html>
PHP
<?php
// about.php
define("SITE_NAME", "My Blog");
$pageTitle = "About Us";

require __DIR__ . "/header.php";
?>
<h2>About Us</h2>
<p>We're a team passionate about technology.</p>
<?php
require __DIR__ . "/footer.php";
?>
💡 Tip: This modular approach is PHP's original design pattern. When you eventually learn Laravel, you'll recognize that Blade's @include, @extends, and @section directives are the modern evolution of this exact idea.

❓ よくある質問

Q Should I use const or define()?
A Use const for simple global constants — it's faster and cleaner. Use define() when you need a runtime-computed value or need to define inside a condition or function. Inside a class, only const works.
Q include or require — which one?
A Default to require. Missing config files and function libraries should trigger an immediate error. The cases for include are rare — optional content like ad placements or analytics snippets where the page should still work without them.
Q Why does require fail even though the file definitely exists?
A 99% of the time it's a path issue. Debug it: echo __DIR__ . "/config.php" to confirm the full path being built. Remember that relative paths are relative to the current working directory, not the script's directory — that's why __DIR__ is the safest way to build paths.

📖 まとめ

📝 練習問題

  1. Create a config.php that defines constants for site name, database host, and upload directory path. Then require it from another PHP page and use the constants to output your configuration.
  2. Split a blog page into header.php, footer.php, and index.php. Use __DIR__ to build all path references in your require statements.
  3. Write code that uses defined() to check whether a constant has been defined, and set a default value if it hasn't.
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%