DONATE Hyvor Developer
PHP
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

PHP Constants

In the real world, a constant is a thing that does not change

Same theory in the programming world, constant is a piece of information stored in the computer's memory which does not change (cannot be changed).

PHP Constants

  • Once a constant is defined, it cannot be changed.
  • All the constants have global scopes, even it is defined inside a function.
  • Unlike variables, constants do not have $ before the name.
  • A constant name should start with a letter or underscore.
  • A constant name can have letters, numbers, ASCII characters between 127-255 after the first letter.

PHP Declaring Constants

PHP does not have a keyword to declare a constant. We have to use define() function for the purpose.

define() Syntax

define(name, value, case-insensitive)

Parameters:

  • name: The name of the constant
  • value: The value of the constant - only boolean, integer, float, and string prior to 5.6. Arrays can be used from PHP 5.6 onwards. (See data types chapter to learn about booleans, integers, floats, strings, and arrays.)
  • case-insensitive: Specify whether the constant is case-insensitive or not. The default is false (case-sensitive).

PHP Constants Example


<?php
// Valid constant names
define("GREETING", "Hello World");
define("GREETING2", "Hello You");
define("GREETING_3", "Hello everyone");

// Invalid constant names
define("2GREETING", "Hello");

echo GREETING, '<br>';
echo GREETING2, '<br>';
echo GREETING_3, '<br>';

Run Example ››

All of above constants are case sensitive

PHP Constants Case-Insensitive Example


<?php
define('GREETING', 'Hello World', true);

echo GREETING, '<br>';
echo Greeting, '<br>';
echo gReeting, '<br>';

Run Example ››

Here, all GREETING, Greeting, and gReeting is equal because the constant is case-insensitive.

Constants are Global

All the constants have global scopes. We can use constants within the functions directly.

PHP Constants are Global Example


<?php
define('GREETING', 'Hello World');

function hello() {
	echo GREETING;
}

hello();

Run Example ››

You can even define constants inside functions and use them outside of it.

PHP Constants: Defining Inside Functions Example


<?php
function defineConstant() {
	define('GREETING', 'Hello World');
}
defineConstant();
echo GREETING;

Run Example ››
0
240