PHP Constants

PHP constant is a name or an identifier for a simple value which can’t change throughout the execution of the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Numbers and underscore is better to come after letters. Constants may have different types of values and they get determined by ‘define(‘name’, value) ‘ function. Another way is to determine them in ‘const name= value’ model since php 5.3 comes. The usage is to avoid repeating long values in your program.

Note: Unlike variables, constants are automatically global across the entire script. By default constant is case-sensitive. Constant identifiers are always uppercase.If you have defined a constant, it can never be changed or undefined.

Creating a PHP Constant:

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

The example below creates a constant with a case-sensitive name:

<?php
define('pi', 3.141516);
echo pi;  // Prints 3.141516
const R= 8.314;
echo R;   // Prints 8.314
?>

Constants can’t change along the program and they don’t have ‘$’ sign at the first. They are accessible just by names of them. If you use second method, you must use it at the top of your program but the first method has no restriction.

Some valid constant names

define("TESTVALUE",     "valid");
define("TESTVALUE2",    "valid");
define("TESTVALUE_3", "valid");

Invalid constant names

define("2TESTVALUE",    "invalid ");
define("__TESTVALUE__", "invalid ");

Seven predefined constants are existing in PHP (they are categorized in magic methods). Some of them have usages which I will explain in detail, later. They all begin and end with two underscore. The three first are case insensitive. Let me illustrate them in example below:

<?php
Echo __Line__  // Prints Line Number this echo code is.
Echo __FILE__  // Prints this php file location.
Echo __dir__ // Prints this php directory location.
Echo __FUNCTION__  //Prints current function name
Echo __CLASS__  // Prints current class name.
Echo __METHOD__  // Prints current class method name.
Echo __NAMESPACE__  // Prints current name of namespace.
?>

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote