0% complete

PHP Basics · Lesson 2 of 8

Constants

Declare values that should not change during a request.

Lesson

A constant is an identifier for a value that should remain fixed while a PHP script runs. Define a named constant with the const keyword in a class or with define() at runtime. Constants are useful for stable settings, but sensitive or deployment-specific configuration belongs in environment configuration rather than source code. In modern PHP, prefer const for compile-time constants and clear, uppercase names by convention. Further guidance Inspect a value before relying on an implicit conversion. Keep input validation separate from casting, use strict comparisons when type matters, and choose an explicit representation for values such as money or optional data. Try normal, empty, and unexpected inputs so the result is deliberate. Practice task: Create a fresh example for Constants. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

Define a constant
PHP
const SITE_NAME = "Learning Lab";
echo SITE_NAME;
Expected output
Learning Lab

Key points

  • Declare values that should not change during a request.
  • Validate external data before converting or using it.
  • Use strict comparisons when both value and type matter.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.