Loading...
Loading...
00:00:00

Constant in PHP

In PHP, a constant is a value that cannot be changed during the execution of a script. Once a constant is defined, it remains the same throughout the execution of the script. Constants are typically used to store values that are needed throughout the script, such as configuration settings or mathematical constants.

Constants in PHP are defined using the define() function, which takes two arguments: the name of the constant and its value. Here's an example:

define("PI", 3.14159);

In this example, we define a constant named "PI" and give it the value of 3.14159. Once this constant has been defined, we can use it throughout the script:

$radius = 5;
$area = PI * $radius * $radius;
echo "The area of the circle is: " . $area;

In this example, we use the constant "PI" to calculate the area of a circle.

Constants in PHP have a few key characteristics:

  1. Constants are case-sensitive: The name of a constant is case-sensitive, so "PI" and "pi" would be two different constants.

  2. Constants can only contain scalar data types: Constants can only be defined as scalar values, such as integers, floats, strings, or booleans.

  3. Constants are global: Constants are defined in the global namespace, so they can be accessed from any part of the script.

  4. Constants cannot be redefined: Once a constant has been defined, it cannot be redefined or undefined during the execution of the script.

define() function

The define() function in PHP takes three parameters:

  1. The name of the constant
  2. The value of the constant
  3. An optional boolean parameter that specifies whether the constant name should be case-insensitive. This parameter is set to false by default, which means that the constant name is case-sensitive.

Here's an example of defining a case-insensitive constant:

define("MY_CONST", "Hello, world!", true);

In this example, we define a constant named "MY_CONST" and give it the value "Hello, world!". The third parameter is set to true, which means that the constant name is case-insensitive. This means that we can refer to the constant as "MY_CONST", "my_const", or "My_Const" and it will always have the same value.

echo MY_CONST;      // Output: "Hello, world!"
echo my_const;      // Output: "Hello, world!"
echo My_Const;      // Output: "Hello, world!"

Here's another example of defining a constant in PHP:

define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database_name");

In this example, we define four constants to store database connection information. We can then use these constants in our database connection code:

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

NOTE: Constants are automatically global and can be used in anywhere in entire script.