phpPHP
Module 13: ConstantsBeginner35 min read

Constants (define vs const), Class Constants & Magic Constants

Compare compile-time const vs runtime define(), typed class constants (PHP 8.3), and magic constants (__DIR__, __FILE__, __LINE__, __CLASS__).

Key Takeaways & Core Concepts
  • `const`: Evaluated at compile time; respects namespaces and class visibility (public const, private const). Cannot be used inside if blocks.
  • `define()`: Evaluated at runtime; can be conditional.

1. `const` vs. `define()`

  • `const`: Evaluated at compile time; respects namespaces and class visibility (public const, private const). Cannot be used inside if blocks.
  • `define()`: Evaluated at runtime; can be conditional.
1. const, Class Constant & Magic Constants
1<?php
2const APP_ENV = "production";
3class Http { public const OK = 200; }
4
5echo APP_ENV . " | Status: " . Http::OK . " | Line: " . __LINE__ . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
5 lines
Note: Demonstrates namespace-level `const`, class constant `Http::OK`, and `__LINE__`.

2. Magic Constants

__DIR__, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __NAMESPACE__ resolve dynamically to the current file/line context.

Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)