PHP variable usage in php learning Notes

Source: Internet
Author: User
Tags require variable scope

If you define variables and constants, how many aspects will you pay attention? You may think:

• How to Define variables? What is the difference between variables and C?
• Are variables case sensitive?
• Are there other important PHP variables?

• Are constants and variables defined in the same way?
Let's talk about it separately.


1. How to define a variable? What is the difference between it and C?
Variables in PHP are represented by a dollar sign followed by the variable name. Variable names are case sensitive. For example:

The code is as follows: Copy code

<? Php
$ Var = 'Jim ';
$ VAR = 'Kimi;
Echo "$ var, $ VAR"; // output "Jim, Kimi"
?>

You may also care about variable naming, which is actually the same as most languages.
2. Are variables case sensitive?
As stated in 1, it is case sensitive.
Note: Since PHP4, the concept of reference assignment has been introduced, which is similar to that of most languages. However, I think C/C ++ is the most similar. because it also uses the "&" symbol.


For example:

The code is as follows: Copy code
1 <? Php
2 $ foo = 'Bob'; // assign 'Bob' to foo.
3 $ bar = & $ foo; // reference through $ bar. Note & symbol
4 $ bar = "My name is $ bar"; // modify $ bar
5 echo $ bar;
6 echo $ foo; // $ foo is also modified.
7?>


Like other languages, you can only reference variables with variable names.


To put it bluntly, the variable in php parses the value of a variable into a variable name and reads the value of that variable name. Instance:

The code is as follows: Copy code

 

<? Php
$ A = "China"; // variable
$ B = "a"; // variable B
$ China = "I'm Chinese! "; // Variable China
$ F = "B"; // variable f
   
Echo $ a. "<br/>"; // output China
Echo $ a. "<br/>"; // output I'm Chinese -- to resolve a variable, add a $ symbol to the front.
$ A = "f"; // change the name to which the variable points (here is the application of the variable)
Echo $ a. "<br/>"; // output B after pointing to the f variable above
$ A = "B"; // same as above
Echo $ a. "<br/>"; // output
   
Echo $ B. "<br/>"; // output
Echo $ B. "<br/>"; // output B
Echo $ B. "<br/>"; // output
   
Echo $ f. "<br/>"; // output B
Echo $ f. "<br/>"; // output
Echo $ f. "<br/>"; // output B
Echo $ f. "<br/>"; // output
   
$ A = "China"; // the last variable has been changed to the value of $ a = $ B, which is changed to B.
Echo $ B. "<br/>"; // output China
Echo $ B; // output I'm Chinese
?>

Note: Variable variables cannot be applied to $ this and Super global variables (the scope of php variables is different from that of other advanced programming languages. View code)

The code is as follows: Copy code


<? Php
$ Name = 'Man ';
$ Name = 'abc'; // if there is no man variable in advance. Create a new man variable. Then assign the abc value.
$ Name = 'Def ';
Echo $ man. "<br/>"; // output abc
Echo $ abc; // output def
   
Echo "<br/> Function show ()
    {
Global $ name; // The global is not set as a global variable. But references
Echo $ name. "<br/>"; // output man
    }
   
Function showtwo ()
    {
// Global $ name;
// Echo $ name. "<br/> ";
Echo $ GLOBALS ['name']; // an array of super global variables
    }
   
Show ();
Showtwo ();
?>

Variable functions:

The code is as follows: Copy code

<? Php
Function B ()
        {
Echo "this is B ";
        }
Function c ($ name = "China") // set the default value
         {
Echo "this is $ name ";
        }
       
$ A = 'B ';
$ A (); // The function for finding the value
$ A = 'C ';
$ A ();?>

 

 

A typical application of variable variables:

The code is as follows: Copy code

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = utf-8"/>
<Title> Untitled Document </title>
</Head>

<Body>
   
<Div>
<Form action = "#" method = "post">
<Label> name: </label>
<Input type = "text" name = "name"/> <br/>
<Label> pwd: </label>
<Input type = "text" name = "pwd"/> <br/>
<Label> tag: </label>
<Input type = "text" name = "tag"/> <br/>
<Input type = "submit" value = "submit"/>
</Form>
</Div>
<? Php
   
Foreach ($ _ POST as $ key => $ value)
        {       
// Print_r ($ _ POST );
$ Key = $ value;
        }
// Extract ($ _ POST); // import the variable from the array to the current symbol table-find the php Manual by yourself
Echo $ name. "<br/> ";
Echo $ pwd. "<br/> ";
Echo $ tag. "<br/> ";
?>
</Body>
</Html>

Variable scope.


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:

The code is as follows: Copy code

<? Php
$ A = 1;
Include "B. inc ";
?>

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:

The code is as follows: Copy code

<? Php
$ A = 1;/* global scope */

Function Test ()
{
Echo $ a;/* reference to local scope variable */
}

Test ();
?>

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.

The global keyword
First, an example of using global:


Example 12-1. Use global

The code is as follows: Copy code

<? Php
$ A = 1;
$ B = 2;

Function Sum ()
{
Global $ a, $ B;

$ B = $ a + $ B;
}

Sum ();
Echo $ B;
?>
 


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:


Example 12-2. Replace global with $ GLOBALS

The code is as follows: Copy code

<? Php
$ A = 1;
$ B = 2;

Function Sum ()
{
$ GLOBALS ["B"] = $ GLOBALS ["a"] + $ GLOBALS ["B"];
}

Sum ();
Echo $ B;
?>
 


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:


Example 12-3. Examples of hyperglobal variables and scopes

The code is as follows: Copy code

<? Php
Function test_global ()
{
// 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.
Global $ HTTP_POST_VARS;

Print $ HTTP_POST_VARS ['name'];

// Superglobals are valid in any range and they do not require 'global' declarations. Superglobals was introduced in PHP 4.1.0.
Print $ _ POST ['name'];
}
?>
 


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:


Example 12-4. Example of static variables

The code is as follows: Copy code
<? Php
Function Test ()
{
$ A = 0;
Echo $;
$ A ++;
}
?>

 


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:


Example 12-5. Example of using static variables

The code is as follows: Copy code
<? Php
Function Test ()
{
Static $ a = 0;
Echo $;
$ A ++;
}
?>
 


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:


Example 12-6. Static variables and recursive functions

The code is as follows: Copy code

<? Php
Function Test ()
{
Static $ count = 0;

$ Count ++;
Echo $ count;
If ($ count <10 ){
Test ();
   }
$ Count --;
}
?>
 


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.


Example 12-7. Declare static variables

The code is as follows: Copy code

<? Php
Function foo (){
Static $ int = 0; // correct
Static $ int = 1 + 2; // wrong (as it is an expression)
Static $ int = sqrt (121); // wrong (as it is an expression too)

$ Int ++;
Echo $ int;
}
?>

 


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:

The code is as follows: Copy code

<? Php
Function test_global_ref (){
Global $ obj;
$ Obj = & new stdclass;
}

Function test_global_noref (){
Global $ obj;
$ Obj = new stdclass;
}

Test_global_ref ();
Var_dump ($ obj );
Test_global_noref ();
Var_dump ($ obj );
?>

Executing the preceding example will result in the following output:

NULLobject (stdClass) (0 ){}

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

The code is as follows: Copy code

<? Php
Function & get_instance_ref (){
Static $ obj;

Echo "Static object :";
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign a reference value to a static variable
$ Obj = & new stdclass;
   }
$ Obj-> property ++;
Return $ obj;
}

Function & get_instance_noref (){
Static $ obj;

Echo "Static object :";
Var_dump ($ obj );
If (! Isset ($ obj )){
// Assign an object to a static variable
$ Obj = new stdclass;
   }
$ Obj-> property ++;
Return $ obj;
}

$ Obj1 = get_instance_ref ();
$ Still_obj1 = get_instance_ref ();
Echo "/n ";
$ Obj2 = get_instance_noref ();
$ Still_obj2 = get_instance_noref ();
?>

Executing the preceding example will result in the following output:

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

The previous example demonstrates 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.

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.