Define the php constant in detail

  • 2020-06-12 08:35:29
  • OfStack

A constant can be understood as a variable whose value does not change. Once the constant value is defined, it cannot be changed anywhere else in the script. 1 constant consists of an English letter, an underscore, and a number, but the number does not appear as an initial.
In php, the defaine() function is used to define constants, and the syntax is:
define(string constant_name, mixed value, case_sensitive = true)

The function takes three arguments:
constant_name: Required parameter, constant name, or identifier
value: Required parameter, value of constant
case_sensitive: Optional parameter that specifies whether case sensitive or not, set to true for insensitive

There are two ways to get a constant value:
1. Use the constant name to get the value directly;
Use the constant() function.

constant() function and direct use of constant name output effect is the same, but the function can dynamically output different constants, in the use of flexible, convenient.

The syntax format is:

mixed constant(string constant_name)

The parameter constant_name is the name of the constant to get or the variable that stores the constant name.

Returns the value of the constant on success, and an error message on failure that the constant is not defined.

To determine if a constant has been defined using the defined() function. The syntax format of the function is:

bool defained(string constants_name)

constant_name to get the name of the constant, returns true if it exists, false if it does not;

Predefined constants can be used in php to obtain information in php. Such as "_FILE_", "_LINE_", "PHP_OS" and so on.

Ex. :


<?php
  define ("MESSAGE", "PHP Constants defined , Constant names are case sensitive ");
  echo MESSAGE."<br/>";    // Output constant MESSAGE
  echo Message."<br/>";    // The output "Message" , indicates that there is no such constant 

  define("MESSAGE2", "PHP Constants defined , Constant names are case insensitive ", true);
  echo MESSAGE2."<br/>";   // Output constant MESSAGE2
  echo Message2."<br/>";   // Output constant 

  $constant_name = "message2";
  echo constant($constant_name)."<br/>";   // Output constant MESSAGE2
  echo defined("MESSAGE")."<br/>";         // If the definition returns true,echo The output shows 1
 ?>


Related articles: