PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP 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 FinishingPHP OOPPHP Object Oriented ProgrammingPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP Interfaces

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

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:

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 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 ››

Why Contansts?

Facebook Twitter