PHP Learning notes PHP variable usage _php tutorial

Source: Internet
Author: User
Variables are an essential part of PHP programming, in PHP variables are divided into global variables and private variables, the following to share my knowledge of PHP variables and usage, we can refer to the reference.

If you have a definition of variables and constants, how many things do you notice? You might think:

• How do I define a variable, and how does it differ from languages like C #?
• Is the variable case-sensitive?
Are there any other important variables in the php?

• Are constants and variables defined the same way?
Tell it separately.


1. How do I define a variable, and how does it differ from languages like C #?
Variables in PHP are represented by a dollar sign followed by a variable name. Variable names are case-sensitive. For example:

The code is as follows Copy Code

$var = ' Jim ';
$VAR = ' Kimi;
echo "$var, $VAR";//Output "Jim,kimi"
?>

You may also be concerned about the naming of variables, which are in fact the same as most languages.
2. Is the variable case-sensitive?
As in 1, it is case-sensitive.
Note that the concept of reference assignment has been introduced since PHP4, but it is similar to most language references, but I think the most similar is C/s + +. Because it also uses the "&" symbol.


For example:

The code is as follows Copy Code
1 2 $foo = ' bob ';//Assign the value ' Bob ' to Foo
3 $bar = & $foo; Referenced by $bar. Note & Symbols
4 $bar = "My name is $bar"; Modify $bar
5 echo $bar;
6 echo $foo; $foo has also been modified.
7?>


As with other languages, only variables with variable names can be referenced


The mutable variable in PHP is simply to parse the value of a variable into a variable name to read the value of that variable name. Instance:

code as follows copy code

$a = "China"; Variable A
$b = "a"; Variable b
$China = "I ' m Chinese!"; Variable China
$f = "B"; Variable F

echo $a. "
"; Export China
echo $ $a. "
"; Output I ' m Chinese--here like to be resolved as a mutable variable, you must add a $ symbol to the front
$a = "F"; Change the name that the variable points to (this is the application of the mutable variable)
echo $ $a. "
"; After the above point to the variable F output b
$a = "B"; Ditto
echo $ $a. "

"; Output A

echo $b. "
"; Output A
echo $ $b. "
"; Output b
echo $$ $b. "

"; Output A

echo $f. "
"; Output b
echo $ $f. "
"; Output A
echo $$ $f. "
"; Output b
echo $$$ $f. "

"; Output A

$ $a = "China"; The last one in front has changed the variable to B so-called $ $a = $b is the value of the changed $b
echo $b. "
"; Export China
echo $ $b; Output I ' m Chinese
?>

Note: mutable variables cannot be applied to $this and hyper-global variables (the scope of PHP variables differs from other advanced programming languages.) See Code)

The code is as follows Copy Code


$name = ' man ';
$ $name = ' abc '; If there is no man this variable beforehand. Just create a new man variable. and assign ABC to the past.
$$ $name = ' def ';
echo $man. "
"; Output ABC
Echo $abc; Output def

echo "

";
Function Show ()
{
Global $name; The global is not set to a globally variable. Instead of referencing
echo $name. "
"; Output man
}

function Showtwo ()
{
Global $name;
echo $name. "
";
echo $GLOBALS [' name ']; Array of hyper-global variables
}

Show ();
Showtwo ();
?>

Variable function:

The code is as follows Copy Code

Function B ()
{
echo "This is B";
}
Function C ($name = "China")//Set default value
{
echo "This is $name";
}

$a = ' B ';
$a (); The function where the value is found
$a = ' C ';
$a ();?>

A typical application of variable variables:

The code is as follows Copy Code





Untitled Document







foreach ($_post as $key = $value)
{
Print_r ($_post);
$ $key = $value;
}
Extract ($_post); Import variables into the current symbol table from an array-find PHP manuals by yourself
echo $name. "
";
echo $pwd. "
";
echo $tag. "
";
?>

Variable scope.


Variable Range
The scope of a variable is the context in which it is defined (translator: plainly, that is, its effective scope). Most PHP variables have a single range. This separate scope span also contains the files introduced by include and require. Example:

The code is as follows Copy Code

$a = 1;
Include "B.inc";
?>

Here the variable $a will take effect in the include file B.inc. However, in a user-defined function, a local function scope is introduced. Any variables that are used inside the function will be limited to the local function in the default context. Example:

The code is as follows Copy Code

$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 refers to a local version of the variable $a, and within that range, it is not assigned a value. You may notice that the global variables in PHP are a little different from the C language, and in C, global variables are automatically applied in functions unless overridden by local variables. This can cause some problems, and some people may inadvertently change a global variable. A global variable in PHP must be declared global when used in a function.

The Global keyword
First, an example of using global:


Example 12-1. Using Global

The code is as follows Copy Code

$a = 1;
$b = 2;

function Sum ()
{
Global $a, $b;

$b = $a + $b;
}

Sum ();
Echo $b;
?>


The output of the above script will be "3". The global variable $a and $b are declared in the function, and all reference variables of any variable are pointed to the global variable. PHP has no restrictions on the maximum number of global variables a function can declare.

The second way to access variables globally is to customize $GLOBALS arrays with special PHP. The previous example can be written as:


Example 12-2. Replace Global with $GLOBALS

The code is as follows Copy Code

$a = 1;
$b = 2;

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

Sum ();
Echo $b;
?>


In $GLOBALS array, each variable is an element, the key name corresponds to the variable name, and the contents of the value variable. $GLOBALS exists globally because $GLOBALS is a hyper-global variable. The following example shows the usefulness of a hyper-global variable:


Example 12-3. Examples of hyper-global variables and scopes are shown

The code is as follows Copy Code

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 scope, and they do not require a ' global ' statement. Superglobals was introduced in PHP 4.1.0.
Print $_post[' name '];
}
?>


Using static variables
Another important feature of the variable range is the static variable (variable). A static variable exists only in the local function domain, but its value is not lost when the program executes away from the scope. Take a look at the following example:


Example 12-4. Example of a static variable that needs to be shown

The code is as follows Copy Code
function Test ()
{
$a = 0;
echo $a;
$a + +;
}
?>


This function is of little use because the value of $a is set to 0 and output "0" each time it is called. Adding a variable to the $a + + does not work because the variable $a does not exist once you exit the function. To write a count function that does not lose this count value, define the variable $a as static:


Example 12-5. Examples of using static variables

The code is as follows Copy Code
function Test ()
{
static $a = 0;
echo $a;
$a + +;
}
?>


Now, each call to the Test () function outputs the value of the $a and adds one.

Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, because they can be recursive indefinitely. You must ensure that there is sufficient method to abort the recursion. This simple function recursively counts to 10, using a static variable $count to determine when to stop:


Example 12-6. static variables and recursive functions

The code is as follows Copy Code

function Test ()
{
static $count = 0;

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


Note: Static variables can be declared according to the example above. If you assign a value to a declaration with the result of an expression, it causes a parse error.


Example 12-7. declaring static variables

The code is as follows Copy Code

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;
}
?>


References to global and static variables
In the Zend engine 1 generation, the PHP4 was driven, and the static and global definitions for the variables were implemented in references manner. For example, a real global variable imported with a global statement inside a function field actually establishes a reference to a global variable. This may lead to unexpected behavior, as demonstrated in the following example:

The code is as follows Copy Code

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);
?>

Performing the above example will result in the following output:

Nullobject (StdClass) (0) {}

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

code as follows copy code

"!--? php
function &get_inst Ance_ref () {
static $obj;

Echo "Static object:";
Var_dump ($obj);
if (!isset ($obj)) {
//assigns a reference 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)) {
//assigns an object to a static variable
$obj = new Stdclass;
}
$obj->property++;
return $obj;
}

$obj 1 = get_instance_ref ();
$still _obj1 = Get_instance_ref ();
echo "/n";
$obj 2 = Get_instance_noref ();
$still _obj2 = Get_instance_noref ();
?>

Performing the above example will result in the following output:

Static object:nullstatic object:nullstatic object:nullstatic object:object (StdClass) (1) {[Property]]=> Int (1)}

The example above 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

http://www.bkjia.com/PHPjc/628777.html www.bkjia.com true http://www.bkjia.com/PHPjc/628777.html techarticle variables are an essential part of PHP programming, in PHP variables are divided into global variables and private variables, the following to share my knowledge of PHP variables and usage, we can refer to the reference ...

  • 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.