PHP Function Reference

PHP constant() Function



The PHP constant() function returns the value of the constant specified by the give name.

This function also works with class constants.

Syntax

constant(name)

Parameters

name Required. Specify the name of the constant.

Return Value

Returns the value of the constant, or null if the constant is not defined.

Exceptions

Generates an E_WARNING level error if the constant is not defined.

Example: constant() example

The example below shows the usage of constant() function.

<?php
//defining a constant
define("Greeting", "Hello world!");

//displaying the value of the constant
echo Greeting."\n";
echo constant("Greeting")."\n";
?>

The output of the above code will be:

Hello world!
Hello world!

Example: using with class constants

Consider one more example where this function is used with class constants.

<?php
interface bar {
  const test = 'Hello';
}

class foo {
  const test = 'World!';
}

echo constant('bar::test')."\n"; 
echo constant('foo::test')."\n"; 
?>

The output of the above code will be:

Hello
World!

❮ PHP Miscellaneous Reference