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
includeandrequire.
1. define() vs const
PHP gives you two ways to declare constants:
<?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 |
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
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
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
// 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
// ❌ 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";
?>
__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
// config.php
const DB_HOST = "localhost";
const DB_NAME = "myapp";
?>
<?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 |
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
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/config.php"; // Second call does nothing
?>
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
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:
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
// 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
// footer.php
?>
</main>
<footer>
<p>© <?= date("Y") ?> <?= SITE_NAME ?></p>
</footer>
</body>
</html>
<?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";
?>
@include, @extends, and @section directives are the modern evolution of this exact idea.
❓ よくある質問
const or define()?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.include or require — which one?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.require fail even though the file definitely exists?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.📖 まとめ
const(global, fast) anddefine()(dynamic) are the two ways to declare constants- Constant names use
SCREAMING_SNAKE_CASEwith no$prefix - Magic constants:
__DIR__(directory),__FILE__(file path),__LINE__(line number) requiretriggers a Fatal Error when the file is missing;includeonly gives a Warning__DIR__is the most reliable way to build file pathsrequire_onceprevents duplicate loading of function/class definitions
📝 練習問題
- Create a
config.phpthat defines constants for site name, database host, and upload directory path. Thenrequireit from another PHP page and use the constants to output your configuration. - Split a blog page into
header.php,footer.php, andindex.php. Use__DIR__to build all path references in yourrequirestatements. - Write code that uses
defined()to check whether a constant has been defined, and set a default value if it hasn't.