[PHP series tutorial] (4) -- PHP Variables

Source: Internet
Author: User
Tags setcookie
Document directory
  • I. Basic Knowledge
  • Ii. Pre-Defined variables
  • Iii. variable range
  • Iv. Variable
  • V. php external variables

I am honored to have been recommended to the homepage by the moderator in my previous article. I am so excited. Continue to study hard. This chapter describes the variables in PHP. It mainly includes pre-defined variables, variable ranges, variable variables, and PHP external variables.

 

I. Basic Knowledge

In PHP, a dollar sign is followed by a variable name, that is, a variable. Variable names are case sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name must start with a letter or underline followed by any number of letters, numbers, or underscores. According to the regular expression, it will be expressed as: '[A-Za-Z _/x7f-/xFF] [a-zA-Z0-9 _/x7f-/xFF] *'

Note: The letter is a-Z, A-Z, ASCII characters from 127 to 255 (0x7f-0xff ).
<? Php <br/> $ Var = "Bob"; <br/> $ Var = "Joe"; <br/> echo "$ var, $ Var "; // outputs "Bob, Joe" </P> <p> $4 site = 'not yun'; // invalid; starts with a number <br/> $ _ 4 site = 'not yun'; // valid; starts with an underscore <br/> $ t? Yte = 'mansikka '; // valid; 'region is (extended) ASCII 228. <br/>?>

In PHP 3, values are always assigned to variables. That is to say, when you assign the value of an expression to a variable, the value of the entire original expression is assigned to the target variable. This means that, for example, changing the value of one variable when the value of a variable is assigned to another variable does not affect another variable.

PHP 4 provides another way to assign values to variables: assign values to input addresses. This means that the new variable simply references the original variable (in other words, "become its alias" or "point. Changing new variables will affect the original variables, and vice versa. This also means that no copy operation is executed. Therefore, this assignment operation is faster. However, any speed-up operation can only be noticed in close loops, large arrays, or objects.

Assign values using the transfer address. simply append a (&) symbol to the variable to be assigned (source variable ). For example, the following code snippet outputs 'My name is bob' twice ':

<? Php <br/> $ Foo = 'bob'; // assign the value 'bob' to $ Foo <br/> $ bar = & $ Foo; // reference $ Foo via $ bar. <br/> $ bar = "My name is $ bar"; // alter $ bar... <br/> echo $ bar; <br/> echo $ Foo; // $ foo is altered too. <br/>?>

It is important to note that only named variables can assign values to addresses.

<? Php <br/> $ Foo = 25; <br/> $ bar = & $ Foo; // This is a valid assignment. <br/> $ bar = & (24*7); // invalid; references an unnamed expression. </P> <p> function test () <br/>{< br/> return 25; <br/>}</P> <p> $ bar = & Test (); // invalid. <br/>?>

Ii. Pre-Defined variables

PHP provides a large number of predefined variables. Because many variables depend on the version and settings of the running server, and other factors, there is no detailed description document. Some predefined variables do not take effect when PHP is run as a command line.

Warning in PHP 4.2.0 and later versions, the default value of the php Command register_globals is off. This is a major change in PHP. Setting the value of register_globals to off affects the validity of the predefined variable set within the global range. For example, to obtain the document_root value, you must replace $ _ server ['document _ root'] with $ document_root, as shown in the following figure, use $ _ Get ['id'] instead of $ id from URL http://www.example.com/test.php? In id = 3, get the id value, or use $ _ env ['home'] instead of $ home to get the value of the environment variable home. Variable: Super global variables cannot be used as variable variables.

If some variables in variables_order are not set, their corresponding PHP pre-defined arrays are also empty.

2.1 super global variables of PHP

$ Globals
Contains a reference to a variable that is valid globally for each current script. The key of the array is the name of the global variable. $ Globals array exists from PHP 3.

$ _ Server
Variables are set by the Web server or directly associated with the execution environment of the current script. Similar to the old $ http_server_vars array (still valid, but not used ).

$ _ Get
Variables submitted to the script through the http get method. Similar to the old $ http_get_vars array (still valid, but not used ).

$ _ Post
Variables submitted to the script through the http post method. Similar to the old $ http_post_vars array (still valid, but not used ).

$ _ Cookie
Variables submitted to the script through HTTP cookies. Similar to the old $ http_cookie_vars array (still valid, but not used ).

$ _ Files
Variables submitted to the script by uploading the http post file. Similar to the old array $ http_post_files array (still valid, but not used ).

$ _ Env
Variables submitted to the script in the execution environment. Similar to the old $ http_env_vars array (still valid, but not used ).

$ _ Request
This array is not trustworthy because the get, post, and cookie mechanisms are used to submit scripts to variables. All the existence or not of the variables contained in the array and the order of the variables are defined according to the variables_order configuration instructions in PHP. ini. This array does not directly simulate earlier versions of PHP 4.1.0.
Note: Since PHP 4.3.0, the file information in $ _ FILES no longer exists in $ _ request.

Warning when running in command line mode, this array will not contain argv and argc entries; they already exist in the array $ _ server.

Iii. variable range

The scope of a variable is the context defined by it ). Most PHP variables have only one separate range. This separate range span also contains the files introduced by include and require. Example:

<? Php <br/> $ A = 1; <br/> include "B. Inc"; <br/>?>

The variable $ A will take effect in the included file B. Inc. However, in user-defined functions, a local function range will be introduced. By default, any variable used in a function is limited to a local function. Example:

<? Php <br/> $ A = 1;/* global scope */</P> <p> function test () <br/>{< br/> echo $; /* reference to local scope variable */<br/>}</P> <p> test (); <br/>?>

This script does not have any output, because the echo statement references a local version of variable $ A and is not assigned a value within this range. You may notice that the global variables in PHP are a little different from those in C language. In C language, global variables automatically take effect in functions unless they are overwritten by local variables. This may cause some problems. Some may carelessly change a global variable. Global variables in PHP must be declared as global when used in functions.

3.1 Global keyword

Code 1: Use the Global keyword

<? Php <br/> $ A = 1; <br/> $ B = 2; </P> <p> function Sum () <br/>{< br/> global $ A, $ B; </P> <p> $ B = $ A + $ B; <br/>}</P> <p> sum (); <br/> echo $ B; <br/>?>

The output of the above script is "3 ". Specify the global variables $ A and $ B in the function. All referenced variables of any variable point to the global variable. PHP has no limit on the maximum number of global variables that a function can declare.

The second way to access variables globally is to use a special PHP custom $ globals array. The preceding example can be written as follows:
Code 2: replace Global with $ globals
<? Php <br/> $ A = 1; <br/> $ B = 2; </P> <p> function Sum () <br/> {<br/> $ globals ["B"] = $ globals ["A"] + $ globals ["B"]; <br/>}</P> <p> sum (); <br/> echo $ B; <br/>?>

In the $ globals array, each variable is an element. The key name corresponds to the variable name and value variable content. $ Globals exists globally because $ globals is a super global variable. The following example shows how to use a super global variable:

Code 3: Examples of hyperglobal variables and scopes

<? Php <br/> function test_global () <br/> {<br/> // most of the predefined variables are not "super ", they need to use the 'global' keyword to make them valid in the local area of the function. <Br/> global $ http_post_vars; </P> <p> Print $ http_post_vars ['name']; </P> <p> // superglobals are valid in any range and they do not require the 'global' statement. Superglobals was introduced in PHP 4.1.0. <Br/> Print $ _ post ['name']; <br/>}< br/>?>

3.2 use static variables

Another important feature of variable range is static variable ). Static variables only exist in local function domains, but their values are not lost when the program runs out of this scope. Take a look at the following example:

Code 1: demonstrate examples of static variables

<? Php <br/> function test () <br/> {<br/> $ A = 0; <br/> echo $ A; <br/> $ A ++; <br/>}< br/>?>

This function is useless, because every call will set the value of $ A to 0 and output "0 ". Adding $ A ++ to the variable does not work, because $ A does not exist once you exit this function. To write a counting function that does not lose the current Count value, you must define variable $ A as static:

Code 2: example of using static variables

<? Php <br/> function test () <br/> {<br/> static $ A = 0; <br/> echo $; <br/> $ A ++; <br/>}< br/>?>

Now, every time you call the test () function, the value of $ A is output and added with one.

Static variables also provide a method for processing recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because infinite recursion may occur. Make sure there are sufficient methods to abort recursion. The simple function calculates 10 recursively and uses the static variable $ count to determine when to stop:
Code 3: static variables and recursive functions

<? Php <br/> function test () <br/> {<br/> static $ COUNT = 0; </P> <p> $ count ++; <br/> echo $ count; <br/> if ($ count <10) {<br/> test (); <br/>}< br/> $ count --; <br/>}< br/>?>

Note: static variables can be declared according to the preceding example. If a value is assigned to the expression result in the declaration, the parsing error occurs.

Code 4: declare static variables

<? Php <br/> function Foo () {<br/> static $ Int = 0; // correct <br/> static $ Int = 1 + 2; // wrong (as it is an expression) <br/> static $ Int = SQRT (121); // wrong (as it is an expression too) </P> <p> $ int ++; <br/> echo $ int; <br/>}< br/>?>

3.3 reference of global and static variables

In the first generation of the Zend engine, PhP4 is driven. The static and Global definitions of variables are implemented in the form of references. For example, a real global variable imported using a global statement within a function domain is actually a reference to a global variable. This may lead to unexpected behaviors, as demonstrated in the following example:

<? Php <br/> function test_global_ref () {<br/> global $ OBJ; <br/> $ OBJ = & New stdclass; <br/>}</P> <p> function test_global_noref () {<br/> global $ OBJ; <br/> $ OBJ = new stdclass; <br/>}</P> <p> test_global_ref (); <br/> var_dump ($ OBJ); <br/> test_global_noref (); <br/> var_dump ($ OBJ); <br/>?>

Executing the preceding example will result in the following output:

NULLobject(stdClass)(0) {}

Similar behavior applies to static statements. References are not stored statically:

<? Php <br/> Function & get_instance_ref () {<br/> static $ OBJ; </P> <p> echo "static object :"; <br/> var_dump ($ OBJ); <br/> If (! Isset ($ OBJ) {<br/> // assign a reference value to a static variable <br/> $ OBJ = & New stdclass; <br/>}< br/> $ obj-> property ++; <br/> return $ OBJ; <br/>}</P> <p> Function & get_instance_noref () {<br/> static $ OBJ; </P> <p> echo "static object :"; <br/> var_dump ($ OBJ); <br/> If (! Isset ($ OBJ) {<br/> // assign an object to a static variable <br/> $ OBJ = new stdclass; <br/>}< br/> $ obj-> property ++; <br/> return $ OBJ; <br/>}</P> <p> $ obj1 = get_instance_ref (); <br/> $ still_obj1 = get_instance_ref (); <br/> echo "/N "; <br/> $ obj2 = get_instance_noref (); <br/> $ still_obj2 = get_instance_noref (); <br/>?>

Executing the preceding example will result in the following output:

Static object: NULLStatic object: NULLStatic object: NULLStatic object: object(stdClass)(1) {  ["property"]=>  int(1)}

The preceding example shows that when a reference is assigned to a static variable, the value of the second call to the & get_instance_ref () function is not remembered.

Iv. Variable

Sometimes it is convenient to use a variable name. That is to say, the variable name of a variable can be dynamically set and used. A common variable is set through declaration, for example:

<? Php <br/> $ A = "hello"; <br/>?>

A variable obtains the value of a common variable as the variable name of the variable. In the preceding example, after using two dollar signs ($), hello can be used as a variable of variable. For example:

<? Php <br/> $ A = "world"; <br/>?>

At this time, both variables are defined: $ A's content is "hello" and $ hello's content is "world ". Therefore, it can be expressed:

<? Php <br/> echo "$ A $ {$ A}"; <br/>?>

The following statement is more accurate and the same result is output:

<? Php <br/> echo "$ A $ hello"; <br/>?>

They all output: Hello world.

To use variables in an array, you must solve an ambiguous problem. When writing $ A [1], the parser needs to know that $ A [1] is used as a variable, you still want $ A as a variable and retrieve the value of [1] In the variable. The syntax for solving this problem is to use $ {$ A [1]} For the first case and $ {$ A} [1] For the second case.

Note: Variable variables cannot be used in PHP's ultra-global variable array. This means that it cannot be used as follows: $ {$ _ Get }. If you want a method to handle super global variables and old HTTP _ * _ vars, you should try to reference them.

V. php external variable 5.1 HTML form (get and post)

When a form body is handed over to a PHP script, the information in the form is automatically available in the script. There are many ways to access this information, such:

Code 1: A simple HTML form
<Form action = "foo. PHP "method =" Post "> <br/> name: <input type =" text "name =" username "> <br/> Email: <input type = "text" name = "email"> <br/> <input type = "Submit" name = "Submit" value = "submit me! "> <Br/> </form> <br/>

There are many ways to access data in HTML forms based on specific settings and personal preferences. For example:

Code 2: access data from a simple post HTML form
<? Php <br/> // available from PhP 4.1.0 </P> <p> Print $ _ post ['username']; <br/> Print $ _ request ['username']; </P> <p> import_request_variables ('P', 'P _'); <br/> Print $ p_username; </P> <p> // available from PHP 3. Starting from PhP 5.0.0, these long pre-defined variables <br/> // can be disabled using the register_long_arrays command. </P> <p> Print $ http_post_vars ['username']; </P> <p> // this parameter is available if the php Command register_globals is on. However, since <br/> // PHP 4.2.0, the default value is register_globals = OFF. <Br/> // This method is not recommended or dependent on. </P> <p> Print $ username; <br/>?> <Br/>

The same applies to get forms, except that appropriate get predefined variables are used. Get also applies to QUERY_STRING (in the URL, "?" ). So, for example, http://www.example.com/test.php? Id = 3 contains get data that can be accessed by $ _ Get ['id.

Note: An array of super global variables, like $ _ post and $ _ get, is available since PHP 4.1.0.

Note: The magic_quotes_gpc configuration command affects the get, post, and cookie values. If it is enabled, the value (it's "php! ") Will be automatically converted to (IT/'s/" php! /"). To insert a database, You must escape it.

Code 3: more complex form variables
<? Php <br/> If (isset ($ _ post ['action']) & $ _ post ['action'] = 'submitted ') {<br/> Print '<PRE>'; </P> <p> print_r ($ _ post); <br/> Print '<a href = "'. $ _ server ['php _ Self ']. '"mce_href = "'. $ _ server ['php _ Self ']. '"> Please try again </a>'; </P> <p> Print '</PRE>'; <br/>} else {<br/>?> <Br/> <form action = "<? PHP echo $ _ server ['php _ Self '];?> "Method =" Post "> <br/> name: <input type =" text "name =" personal [name] "> <br/> Email: <input type = "text" name = "personal [email]"> <br/> beer: <br> <br/> <select multiple name = "beer []"> <br/> <option value = "warthog"> warthog </option> <br/> <option value = "Guinness"> Guinness </option> <br/> <option value = "stuttgarter"> stuttgarter schwabenbr </option> <br/> </SELECT> <BR> <br/> <input type = "hidden" n Ame = "action" value = "submitted"> <br/> <input type = "Submit" name = "Submit" value = "submit me! "> <Br/> </form> <br/> <? Php <br/>}< br/>?>

In PHP 3, arrays used by variables are limited to one-dimensional arrays. In PHP 4, there is no such restriction.

5.2 HTML form (get and post)

When submitting a form, you can use an image to replace the standard submit button with a tag like this:

<Input type = "image" src = "image.gif" mce_src = "image.gif" name = "sub"> <br/>

When a user clicks somewhere in the image, the corresponding form is sent to the server, and two variables sub_x and sub_y are added. They contain the coordinates of user-clicked images. Experienced users may notice that the actual variable name sent by the Browser contains a dot rather than an underline, but PHP automatically converts the dot into an underline.

5.3 HTTP cookies

PHP transparently supports HTTP cookies defined in the Netscape specification. Cookies are a mechanism for storing data on a remote browser and tracking or recognizing users who access them again. You can use the setcookie () function to set cookies. Cookies are part of the HTTP header, so the setcookie function must be called before sending any output to the browser. The Header () function has the same restrictions. Cookie data is available in the corresponding cookie data array, such as $ _ cookie, $ http_cookie_vars, and $ _ request.

If you want to assign multiple values to a cookie variable, you must assign it to an array. For example:

<? Php <br/> setcookie ("mycookie [Foo]", "Testing 1", time () + 3600); <br/> setcookie ("mycookie [bar]", "Testing 2", time () + 3600); <br/>?>

This will create two separate cookies, even though mycookie is a single array in the script. If you want to set multiple values in just one cookie, use serialize () or explode () on the value first ().

Note that a cookie in the browser replaces the previous cookie with the same name, unless the path or domain is different. Therefore, the shopping Box program can keep a counter and pass it together, for example:
Code 1: An Example of setcookie ()

<? Php <br/> If (isset ($ _ cookie ['Count']) {<br/> $ COUNT = $ _ cookie ['Count'] + 1; <br/>}else {<br/> $ COUNT = 1; <br/>}< br/> setcookie ("count", $ count, time () + 3600); <br/> setcookie ("cart [$ count]", $ item, time () + 3600); <br/>?>

5.4 name in the Variable

Generally, PHP does not change the variable name passed to the script. However, it should be noted that point (dot, period, full stop) is not a valid character in the PHP variable name. For the reason, see:

<? Php <br/> $ varname. Ext;/* invalid variable name */<br/>?>

At this time, the parser sees a variable named $ varname followed by a String concatenation operator followed by a bare string (for example, a string without quotation marks, and does not match any known name or reserved word) 'text '. Obviously, this is not the expected result.

For this reason, note that PHP will automatically replace the vertices in the variable name with underscores.
Because PHP determines the variable type and converts it as needed (usually), it is not obvious what type of variable is given at a certain time point. PHP includes several functions to determine the type of a variable, such as GetType (), is_array (), is_float (), is_int (), is_object (), and is_string ().

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.