Understanding Constant in PHP – Updated to PHP 7

Previously, we have discussed variable in PHP, this time, we’ll discuss constant in PHP.

As we already know, PHP provides two places to store values, that are (1) variable and (2) constant.

The characteristic of a variable is that it can be overwritten, means that its value can be changed. Opposite to that, constants are fixed, we can’t change its value.

Because of its nature, constants are often used to save configuration data, such as server, site, and database configuration.

I. Declaring Constant in PHP

In PHP, we can declare constants in two ways, using a define() function or using the keyword: const

1. Declaring Constant in PHP Using define Function

An example:

<?php
define('BASE_URL', 'www.webdevzoom.com');
echo BASE_URL; // www.webdevzoom.com

Note: we can declare constant using define function anywhere within PHP script except inside a class. The following code results an error:

<?php
class siteProp()
{
	define('BASE_URL', 'www.webdevzoom.com'); // Error
	public function getProp()
	{
		// code
	}
}
?>

2. Declaring Constant in PHP Using const Clause

An example:

<?php
const BASE_URL = 'www.webdevzoom.com';
echo BASE_URL; // www.webdevzoom.com

Note: we can declare constant using the keyword const anywhere, but for PHP version < 5.3, we can only use this keyword inside a class

<?php
const SITE_URL = 'www.webdevzoom.com'; // Valid only for PHP >= 5.3
class siteProp
{
	const SITE_URL = 'www.webdevzoom.com'; // Valid
}
?>

3. Tips and The Writing Standard

There are several rules while declaring a constant:

  • Constant name must begin with a letter (a-z, A-Z) or underscore (_) then the rest of the name can contain letters, numbers, and underscores;
  • Constant name is case sensitive, means distinguishing between uppercase and lowercase letters, for define function, optionally we can make it case insensitive;
  • Constants can only be assigned with scalar values, such as boolean, int, float, string, and array (PHP 7), and can not be assigned with object (class).
  • Starting from PHP 7, Constant can be assigned with an array.
  • Constant names can be same as PHP keywords such as echo, but when calling it, we must use the function constant, e.g.
  • <?php
    define('echo', 'www.webdevzoom.com');
    echo constant('echo'); // www.webdevzoom.com
    ?>

More about the differences between define and const will be discussed at the end of this article.

II. Tips While Using Constant In PHP

Some useful tips while choosing constant names:

  1. Choose constant name that reflects its content, e.g: DB_HOST, DB_USER, DB_PASS, etc…
  2. To easily distinguish with others, use capital letters, if it contains more than one word, separate it with underscore, e.g DB_HOST
  3. Avoid names beginning and ending with two underscores, such as: __NAME__, because it will potentially conflict with PHP’s built-in constants. If a conflict occur, PHP will not raise an error message, but our constant’s value changed to the value of built-in constant;
  4. To avoid collision between constants, before we declare a constant, we can test it first whether the constant name already exists using the function defined(), for example:
  5. <?php
    $list = array('SITE_TITLE' => 'WebDevZoom', 'SITE_URL' => 'www.webdevzoom.com');
    foreach($list as $const_name => $const_val)
    {
    	if (!defined($const_name))
    	{
    		define($const_name, $const_val);
    	}
    }
    
    echo SITE_URL; // www.webdevzoom.com
    ?>

III. Constant Scope

Constants are global, once declared, constants can be used anywhere either within or outside a function, for example:

define('SITE_URL', 'www.webdevzoom.com');
function print_url() {
	echo SITE_URL;
}

print_url(); //www.webdevzoom.com

IV. Difference Between define and const

The define function is executed during the runtime, while const at compile time, so it brings up some differences, here are some of them:

  1. define can be declared within a conditional statement, while const not.
  2. <?php
    if (!defined('SITE_NAME'))
    	define('SITE_NAME', 'WebDevZoom'); // Valid
    
    if (defined('SITE_URL'))
    	const SITE_URL = 'www.webdevzoom.com'; // Error
    ?>
  3. Using define, we can assign an expression to the constant, but not for const.
  4. <?php
    define('MAX_EXEC', 60 * 3); // Valid
    define('MAX_TIME', MAX_EXEC + 360); // Valid
    define('FULL_NAME', FIRST_NAME . LAST_NAME) // Valid
    const MAX_EXEC = 60 * 3; // Valid on PHP >= 5.6
    ?>
  5. define can be changed to case insensitive, while const not.
  6. <?php
    define('MAX_EXEC', 180, true); 
    echo MAX_EXEC; // 180
    echo max_exec; // 180
    
    const MAX_TIME = 180;
    echo MAX_TIME; // 180
    echo max_time; // Error
    ?>
  7. Using define, we can combine string and variable to create the constant name, but not for const
  8. <?php
    $list = array('SITE_NAME' => 'WebDevZoom', 'SITE_URL' => 'www.webdevzoom.com');
    foreach($list as $const_name => $const_val)
    {
    	if (!defined($const_name))
    	{
    		define('CFG_' . $const_name, $const_val);
    	}
    }
    echo CFG_SITE_NAME; // WebDevZoom
    ?>
  9. Since it runs at compile time, const is slightly faster than define, this takes effect in the large use of constants.

V. Built-in Constant In PHP

PHP provides ready-to-use constants called magic constant, these constants are based on various extensions, so it is only available when the extension is available either during loading or compilation time.

By default, these constants are already activated, so we can directly use it. Some of them are:

Nama Konstanta Keterangan
__LINE__ Retrieving line number of code where the constant executed.

<?php

echo __LINE__; // 3
?>
__FILE__ Retrieving full path of a php file, an example:

<?php
echo __FILE__; // E:\\xampp\htdocs\tutorial.php
?>
__DIR__ Retrieving full path of a directory of a php file, an example:

<?php
echo __DIR__; // E:xampp-1.8.3.2htdocs
?>
__FUNCTION__ Retrieving a function name, an example:

<?php
function testFunction()
{
	echo __FUNCTION__;
}
testFunction(); // testFunction
?>
__CLASS__ Retrieving class name along with its namespace (PHP 5.3), an example:

<?php
namespace App\Libraries;

class testClass 
{
	public function testMagicConstant()
	{
		echo __CLASS__;
	}
	
}
$class = new testClass;
$class->testMagicConstant(); // App\Libraries\testClass
?>

VI. Some Examples of Constant Usage

Starting from PHP 7, we can assign constants with arrays. This will make us easier to group values. For example, we’ll use constants to save server configuration data:

File: config.php

define ('SITE_NAME', 'WebDevZoom');
define ('DB_CONFIG', ['host' => 'localhost',
			'port' => '3306',
			'db_name' => 'webdevzoom',
			'user' => 'root',
			'pass' => ''
		     ]
	);

File: connect.php

<?php
$conn = mysqli_connect(DB_CONFIG['host'], DB_CONFIG['user'], DB_CONFIG['pass']);
if (!$conn) {
	die('MySQL ERROR: ' . mysqli_connect_error());
}

mysqli_select_db($conn, DB_CONFIG['db_name']);

More…

In this tutorial, we have learned constant in PHP, for more references you can visit its official page at http://php.net/manual/en/language.constants.php

Related Post

One Response

Leave a comment

Like Us

Social