Explanations of variables and constants in PHP

Source: Internet
Author: User
Tags php language variable scope

Almost all programming languages involve the concepts of variables and constants, and PHP is no exception. This section describes how variables and constants in the PHP language are applied.

First, what are variables and constants

During program execution, the value stored by the variable can be changed at any time, and the value stored in the constant cannot be changed.

Variables are used to store temporary data information. When a variable is defined, the system automatically assigns the variable a storage space value. We can assign a value to a variable when it is defined, and if we need to change the value of the variable, simply assign it again. For those temporary data information or process, can be stored in variables.

Constants are used to store data information that is infrequently changed. You can assign a value when you define a constant, which is valid during the entire execution period of the program and cannot be assigned to the constant again.

Second, the definition and assignment of variables

The following variables are explained earlier, but we have not yet systematically explained the application of variables. Let's start by explaining how to implement the definition and assignment of variables in PHP.

1. Definition of a variable

The syntax format for defining a variable in PHP is as follows:

$ variable name = value of variable

When naming a variable, you need to follow these naming conventions:

    • The variable name begins with a letter or a lower line, which can consist of letters, lines, or numbers.
    • Variable names are case-sensitive, and "$var" and "$VAR" represent two different variables respectively.
    • The custom variable name cannot be the same as the default variable name provided by PHP.
    • When naming a variable, try to use a meaningful string.

The variables that meet the specified parameters are named as follows:

$name; $_password; $no 1;

Non-conforming variables are named as follows:

$1book;$*a;

2. Assigning values to variables

There are two ways to assign a value to a variable: value assignment and reference assignment, both of which differ greatly in the way data is processed.

1) Transfer value assignment

This assignment uses "=" To assign the value of one variable (or expression) directly to another variable. With this assignment, the variable values on both sides of the equal sign do not affect each other, and any change in the value of the variable does not affect the other variable. Essentially, the value assignment is achieved by copying a copy of a variable in the storage area. The sample code to apply the value assignment is as follows:

<?php$a = $b = $a; $b = 44;echo "The value of variable A is". $a. "<br>"; echo "The value of variable B is". $b;? >

In the code above, when the "$a = 33" statement is executed, the system creates a storage space for variable A in memory and stores the value of 33 in that storage space. Implementation is shown in procedure 2-14. When the "$b = $a" statement is executed, the system creates a storage space for variable B in memory and copies the contents of variable A to the storage space to the storage space that the variable B points to. Implementation is shown in procedure 2-15.

Figure 2-14 Storage space for a variable a 2-15 to open the storage space of variable B

When the "$b = 44" statement is executed, the system changes the value of the variable B point to storage to 44, while the value of variable a points to the storage space is still 33. Implementation is shown in procedure 2-16. When the program in code 2-14 is executed, the results are shown in 2-17.

Figure 2-16 Changing the value of a variable B figure 2-17 How to assign a value

2) Reference Assignment

Reference assignment also uses "=" To assign the value of a variable to another variable, but it needs to precede the variable to the right of the equal sign with a "&" symbol. In fact, this method of assignment is not a real assignment, but a variable that references another variable. When using a reference assignment, two variables will point to the same storage space in memory, so any change in one variable will cause another variable to change. The sample code to apply the reference assignment is as follows:

<?php$a = $b = & $a; $b = 44;echo "The value of variable A is". $a. "<br>"; echo "The value of variable B is". $b;? >

When you execute the "$a = 33" statement in the code above, the procedure for the memory operation is the same as the value of the pass assignment, which is no longer explained. After executing the $b = & $a statement, the variable B will point to the storage space that the variable a occupies. Implementation is shown in procedure 2-18.

After executing the "$b = 44" statement, the storage space that the variable B points to saves the value to 44. Because variable a also points to this storage space, the value of variable A is also changed to 44.

When the program in code 2-15 is executed, the results are shown in 2-19.

Figure 2-18 variable b points to variable a storage space Figure 2-19 Reference assignment method

Iii. Scope of variables

With PHP language development, we can declare variables almost anywhere, but the variable declaration location and the way we declare it determine the difference in scope. The so-called variable scope, refers to the variable in which range can be used, in which range can not be used. In PHP, you can divide variables into local variables and global variables according to their different scopes.

1. Local variables

A local variable is a variable declared in the body of a function whose scope is limited to the inner part of the function body in which it is located. If the variable is referenced outside the body of the function, the system will assume that the reference is another variable.

The sample code to apply the local variables is as follows:

<?phpfunction Local () {$a = "local variable";//Declare a variable A in the function and assign the value of echo "function internal variable A to". $a. "<br>";} Local (); Call function local (), used to print out the value of variable a $ A = "outside variable."; Declare the variable a again outside the function and assign another value echo "function external variable a value is". $a;? >

When the program is executed, the results are shown in 2-20.

Figure 2-20 Application of local variables

2. Global variables

Global variables can be accessed anywhere in the program, and the scope of this variable is the broadest. To declare a variable as a global variable, simply precede the variable with the "global" keyword (either case-insensitive or global). With global variables, we are able to reference function external parameters within the function, or to reference parameters inside the function outside the function.

The example code that applies global variables is as follows:

<?php$a = "Outside"; Define a variable A (note: $ A is a global variable) function local () {///define a function localglobal $a;//declare variable A as a global variable echo "Gets the value of variable A as" inside the local function. $a. "<br>"; global $b; Declare variable B as a global variable $b = "Inside"; The local function assigns a value of variable b}local (); Outputs the value of the internal variable A of the local function echo "Gets the value of variable B as" outside the local function. $b; Output the value of variable B in the function local external?>

When the program is executed, the results are shown in 2-21.

Figure 2-21 Application of global variables

Note: While applying global variables can make it easier for us to manipulate variables, sometimes the expansion of variable scopes can cause problems in development, and may result in unexpected issues. In general, we do not recommend the use of global variables.

Four, static variables

A variable has not only its specific scope of action, but also its life cycle, the period of its survival. The life cycle of a variable is a time period in which a variable can be used, in which case the variable is valid, and once the time period variable is exceeded, we will not be able to access the value of the variable again.

PHP's lifecycle rules for variables are as follows:

    • The life cycle of a local variable is the entire process in which the function is called. When the function at which the local variable is located ends, the life cycle of the local variable ends.
    • The lifetime of a global variable is the entire process in which the ". php" script file is called. When the global variable is at the end of the script file call, the lifetime of the global variable ends.

Sometimes when a custom function finishes, we want the variable inside the function to still exist, and we need to declare the variable as a static variable. Declare a variable as a static variable by adding the "static" keyword before the variable.

The example code for applying a static variable is as follows:

<?phpfunction Test () {static $a = 0;//defines a static variable A and assigns an initial value of 0echo $a. "<br>"; The value of the output variable A is $ A = $a +1; Assign the value of variable a plus 1 to the variable a}test () again; Call function test () test (); test (); Echo $a; The life cycle of variable a ends and no value is output?>

When the program is executed, the results are shown in 2-22.

Figure 2-22 Application of static variables

As can be seen from the results above, the value of variable a will increase by 1 each time the function test () is called. This means that the variable a still exists after each call to the function. When the function test () is called again, the value of variable a will use the value that was obtained after the last call to the function. We can also conclude from the above example that the scope of the static variable is the same as the local variable, but the life cycle is the same as the global variable.

We can understand static variables this way: only when the function is first called, the initial value of the static variable in the function body is taken. When the function is called again later, the value of the static variable is the value that was obtained when the function was last called.

Note: when assigning an initial value to a static variable, you cannot assign an expression to the static variable.

Five, variable variable

We already know from the previous introduction that when defining a variable in PHP, the variable must have a fixed name. In fact, PHP also supports a special way of using variable variables, variable names are determined by the value of other variables, so the name of the variable is variable. The syntax format for declaring a mutable variable is as follows:

$$ variable variable name = variable variable value

The sample code for applying a mutable variable is as follows:

<?php$a = "Hello"; Define a variable A, and assign a value of hello$ $a = "world"; Defines a mutable variable named the value of the variable A, echo $a. "<br>"; The value of the output variable A is echo $ $a. "<br>"; The value of the output variable variable echo $Hello; Another way to output variable variable values?>

When the program is executed, the results are shown in 2-23.

Figure 2-23 Application of variable variables

Vi. Default System Variables

PHP provides a number of default system variables for obtaining system configuration information, network request-related information, and so on. The name of the default system variable for PHP and its effect are shown in table 2-9.

Table 2-9 PHP default System variables

variables function
$GLOBALS Stores all global variables in the current script, whose key is the variable name, and value is the variable value
$_server Array of current Web server variables
$_get Store data in a form submitted in a Get method
$_post Store data in a form submitted in the Post method
$_cookie Gets or sets the array of variables stored in the user's browser cookies
$_files Stores the data that the upload file submits to the current script
$_env Store current web environment variables
$_request Stores all the request arrays in the submission form, including all the contents of $_get, $_post, $_cookie, and $_session
$_session An array of session variables that store the current script

The default system variables provided by PHP can be viewed by calling the Phpinfo () function. However, due to differences in operating system version, server version, and PHP configuration file, the content displayed in different environments may vary.

vii. definition of constants

In PHP, a constant is defined by the Define () function, which has the following syntax:

BOOL Define (String $name, mixed $value [, BOOL case_$insensitive])

The parameters involved in the above syntax are described below.

    • Name: Specifies the names of the constants.
    • Value: Specifies the values of the constants.
    • Insensitive: Specifies whether the name of the constant is case insensitive. True is not case-sensitive, and is case-sensitive if set to false. If this parameter is not set, the default value of False is taken.

The example code for applying constants is as follows:

<?phpdefine ("COLOR", "Red"); Defines a constant color with a value of Redecho color. "<br>"; The value of the output constant color echo color. "<br>"; The value of the constant color cannot be output correctly define ("SHAPE", "Round", TRUE); Defines a constant shape with a value of round, not distinguished by the case of the name echo shape. "<br>"; The value of the output constant shape echo shape; The value of the output constant shape?>

When the program is executed, the resulting results are shown in 2-24.

Figure 2-24 Application of constants

Note: When naming constants, it is also necessary to follow the naming conventions for variables, and it is recommended to use all uppercase letters. In addition, constants are used differently from variables, and there is no need to precede constants with a "$" symbol.
Viii. Default System Constants

As with the default system variables, PHP also provides some default system constants for use by users. PHP's default system constants can be applied at any time in the program, but we cannot change the values of these constants arbitrarily. Some of the default system constant names commonly used in PHP and their effects are shown in table 2-10.

Table 2-10 PHP Default System constants

Constants function
__file__ Stores the absolute path and file name of the current script (physical address)
__line__ The line number where the constant is stored
__function__ The function name where the constant is stored

__class__

The name of the class where the constant is stored
Php_version Stores the version number of the current PHP
Php_os The operating system that stores the current server

Several "Magic constants" for PHP

name Description
__line__ The current line number in the file.
__file__ The full path and file name of the file. If used in the include file, the include filename is returned. Since PHP 4.0.2,__file__ always contains an absolute path, and the previous version sometimes contains a relative path.
__function__ The name of the function (PHP 4.3.0 new addition). From PHP 5 This constant returns the name (case-sensitive) when the function is defined. In PHP 4, this value is always in lowercase letters.
__class__ The name of the class (PHP 4.3.0 new addition). From PHP 5 This constant returns the name of the class when it is defined (case-sensitive). In PHP 4, this value is always in lowercase letters.
__method__ The method name of the class (PHP 5.0.0 new addition). Returns the name of the method when it is defined (case-sensitive).

Explanations of variables and constants in PHP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.