Developer
PHP
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP VariablesPHP ConstantsPHP OutputPHP Data TypesPHP 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 wolrd, a constant is a thing that does not change

Same theory in the programming world, constant is a storage that 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 does 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: Constant name
  • value: Constant value - only boolean, integer, float and string prior to 5.6. Arrays can be used from PHP 5.6 onwards.
  • 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, GREETING, Greeting and gReeting are 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 ››
Advertisement
0
177