PHP basic syntax - constants

5. Constants

Constants are like variables, but once a constant is defined it cannot be changed or undefined.

1) PHP constants

A constant is an identifier (name) for a single value. This value cannot be changed in script.

Valid constant names start with a character or an underscore (there is no $ sign before the constant name).

Unlike variables, constants are automatically global throughout the script.

To set constants, use the define() function - it takes three arguments:

  1. The first parameter defines the name of the constant
  2. The second parameter defines the value of the constant
  3. An optional third parameter specifies whether the constant name is case-insensitive. The default is false.

The following example creates a case-sensitive constant with the value "Welcome to W3School.com.cn!":

Example:

<?php
define("GREETING", "Welcome to W3School.com.cn!");
echo GREETING;
?>

The following example creates a case-insensitive constant with the value "Welcome to W3School.com.cn!":

Example:

<?php
define("GREETING", "Welcome to W3School.com.cn!", true);
echo greeting;
?>

constants are global

Constants are automatically global and available throughout the entire script.

The following example uses a constant inside a function even though it is defined outside the function:

Example:

<?php
define("GREETING", "Welcome to W3School.com.cn!");

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

 

Guess you like

Origin blog.csdn.net/qq_42133100/article/details/96869380