Content · Programming · PHP

PHP constant() Function: Usage and Examples

Learn how PHP constant works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Reads the value of a defined constant using its name.

What Is constant() in PHP?

Reads the value of a defined constant using its name.

Its syntax is:

constant(string $name): mixed

Parameters:

  • $name — Accepted as string; required argument.

Return type: mixed. Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.

Availability: Core PHP.

Example 1: Basic Usage

<?php

echo constant("PHP_VERSION");

Output:

8.4.24

Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.

Example 2: A Different Input

<?php

echo constant("PHP_INT_SIZE");

Output:

8

Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.

Practical Example: Applying It in a Program

<?php

define("REPORT_LIMIT", 25); $configKeys = ["REPORT_LIMIT", "PHP_INT_SIZE"]; foreach ($configKeys as $configKey) { if (defined($configKey)) { echo $configKey . ": " . constant($configKey) . PHP_EOL; } }

Output:

REPORT_LIMIT: 25
PHP_INT_SIZE: 8

Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.

Important Behavior and Edge Cases

  • Key behavior: Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.
  • Environment: Core PHP.

Comparison With Related Functions

FunctionPurpose
constant()Reads the value of a defined constant using its name.
defined()defined() checks whether a constant exists; constant() returns its value.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Calling constant() with an unknown name throws an ErrorCalling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.

Key Takeaways

  • Reads the value of a defined constant using its name.
  • Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.
  • Core PHP.

Summary: Calling constant() with an unknown name throws an Error. Check defined() first when names are dynamic.

Share this resourceSend this page to someone who may find it useful.