PHP MySQL tutorial

PHP Constants

In PHP, constant is an identifier which holds a constant value. The value of constant cannot be changed while executing the script.

Syntax

Constants are declared by using define() function.

define (name, value, case-insensitive)

Name and value are mandatory parameters. Whereas, case-insensitive is an optional parameter. Its default value is false.

Characteristics of constants

  • Constants do not require $ sign.
  • They start with an alphabet or underscore ( _ ) and contain alphanumeric characters
  • Constants are global and accessible in the entire script.
  • Constants cannot be re-assigned or undefined, once they are defined.
  • Constant names are conventionally defined in uppercase.

Valid and invalid constants identifiers

<?php
	// Valid constant names
	define("DATABASE", "Wordpress");
	define("DATABASE2", "Magento");
	define("DATABASE_SYMPHONY", "Symphony");

	// Invalid constant name
	define("3DATABASE", "Symphony");

	// Valid constant name, but do not suggest as PHP my use same name as magical constant in future, 
	// which may break your script.
	define("__DATABASE__", "Joomla");

	echo DATABASE . "<br>";
	echo DATABASE2 . "<br>";
	echo 3DATABASE . "<br>"; // This will generate an error
	echo __DATABASE__ . "<br>";
?>

Download the code Run the code

const keyword

Alternatively, constant variable can be defined using const keyword.

<?php
	const KH_NAME  = "John";
	echo "My name is " . KH_NAME;
?>

Download the code Run the code

constant () Function

It is used to retrieve the value of constant. It is helpful when you know the name of constant and want to retrieve its value.

<?php
	define("KH_NAME", "My name is John");
	echo constant("KH_NAME");
?>

Download the code Run the code

get_defined_constants() function

It will return the array of constants name and their values. It include the default constants as well as user defined constants.

<?php
	define("KH_DATABASE", "Wordpress");
	define("KH_USER", "John");
	const KH_PASSWORD = "password";

	echo "<pre>";
	print_r(get_defined_constants());
	echo "</pre>";
?>

Download the code Run the code

<<< PHP Data TypesPHP Operators >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .