PHP 7 Constants

Laravel

117

w3alert.com

26-12-2019


PHP Constants

Constants are a type of variable in PHP. In which assign value to a constant variable but its value can not be modified or changed.

NOTE:- For example, if you define a constants variable and do not want to change its value, then we use the PHP constants.

Syntax

define(constant_variable, value, case-insensitive);

Here,

  • constant_variable:- it is the first parameter and required. it is a constant variable.
  • value:- it is a value of a constant variable.
  • case-insensitive:- You can pass two values ​​instead of case_sensitive: True or False. The default value is false.

Rules of Constants

The following rules for understand PHP Constants:

  1. Constants do not require a $ sign like a variable name.
  2. PHP Constants names begin with letters and underscores.
  3. The Variable name cannot be initialized with a number.
  4. The variable name is Case_sensitive, like SKY and sky written in two different forms, but in PHP Constants you can create this type of Case_sensitive by giving the Case_sensitive values ​​(True and False) in a defined function. As shown in the example.
  5. PHP Constants variable that occurs is with the global scope. The constant global variable is accessible to the entire PHP script. Entire variable can also be accessed from anywhere.
  6. PHP Constants already have some defined constants such as: PHP_VERSION, PHP_MAJOR_VERSION, PHP_ZTS, PHP_DEBUG, etc. Which cannot be used to define constants. For more information about PHP predefined constants you can read the official document here https://www.php.net/manual/en/reserved.constants.php
  7. In Constants, Reserved keywords like if, else, etc can be used neither for variable nor for constant_variable.

Examples:

Example 1. Define a constant_variable with a case-sensitive name

<!DOCTYPE html>
<html>
<body>

<?php
// Define variable with case-sensitive
define("WELCOME", "Welcome to w3alert.com!");
echo WELCOME;
?> 

</body>
</html>

Example 2. Define a constant_variable with a case-insensitive name

<!DOCTYPE html>
<html>
<body>

<?php
// Define variable with case-sensitive
define("WELCOME", "Welcome to w3alert.com!");
echo welcome;
?> 

</body>
</html>

PHP Contants are Global

PHP constants are automatically global and the constants global variables can be used for entire scripts.

Example: PHP constants global variable

<!DOCTYPE html>
<html>
<body>

<?php
define("source", "w3alert.com");

function myTest() {
    echo source;
}
 
myTest();
?> 

</body>
</html>