Home  >  Article  >  Backend Development  >  PHP study notes: php variable usage_PHP tutorial

PHP study notes: php variable usage_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:15:40894browse

Variables are an essential thing in PHP programming. Variables in PHP are divided into global variables and private variables. Let me share some of my understanding and usage of PHP variables for your reference.

What aspects would you pay attention to when defining variables and constants? You may think:

•How to define variables, and how is it different from languages ​​such as C#?
•Are variables case sensitive?
•Are there other important PHP variables?

•Are constants and variables defined the same?
Let’s tell them separately.


1. How to define variables, and how is it different from languages ​​such as 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
 代码如下 复制代码

$var='Jim';
$VAR='Kimi;
echo "$var,$VAR";//输出“Jim,Kimi"
?>

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

You may also care about the naming of variables, which is the same as in most languages.
2. Are variables case-sensitive?

As mentioned in 1, it is case sensitive.
 代码如下 复制代码
1 2 $foo = 'Bob'; // 赋值'Bob'给foo
3 $bar = &$foo; // 通过$bar引用.注意&符号
4 $bar = "My name is $bar"; // 修改 $bar
5 echo $bar;
6 echo $foo; // $foo 也修改了.
7 ?>
Note, one thing that needs to be explained is that since PHP4, the concept of reference assignment has been introduced, which is actually similar to references in most languages, but I think the most similar one is C/C++ because it also uses the "&" symbol. For example:
The code is as follows Copy code
1 2 $foo = 'Bob'; // Assign 'Bob' to foo<🎜> 3 $bar = &$foo; // Referenced through $bar. Note the & symbol <🎜> 4 $bar = "My name is $bar"; // Modify $bar<🎜> 5 echo $bar;<🎜> 6 echo $foo; // $foo has also been modified.<🎜> 7 ?>


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


To put it bluntly, variable variables in PHP are to parse the value of a variable into a variable name and read the value of that variable name. Example:

The code is as follows Copy code
 代码如下 复制代码

 

$a = "China"; //变量a
$b = "a"; //变量b
$China = "I'm Chinese !"; //变量China
$f = "b"; //变量f

echo $a."
";  //输出 China
    echo $$a."
"; //输出 I'm Chinese  --这里像要当做可变变量解析,必须在前面多加一个$符号
    $a = "f";  //改变变量指向的名称(这里就是可变变量的应用)
    echo $$a."
"; //经过上面指向变量f后输出 b
    $a = "b"; //同上
    echo $$a."

"; //输出 a
   
    echo $b."
"; //输出 a
    echo $$b."
"; //输出 b
    echo $$$b."

"; //输出 a
   
    echo $f."
"; //输出 b
    echo $$f."
"; //输出 a
    echo $$$f."
"; //输出 b
    echo $$$$f."

"; //输出 a
   
    $$a = "China"; //前面最后一个已经更改了变量为b所谓$$a=$b 也就是改变的$b的值
    echo $b."
"; //输出 China
    echo $$b; //输出 I'm Chinese
?>

 代码如下 复制代码


    $name = 'man';
    $$name = 'abc'; //如果事先没有man这个变量。就新建一个man变量。 然后把abc赋值过去
    $$$name = 'def';
    echo $man."
"; //输出abc
    echo $abc; //输出def
   
    echo "


";
    function show()
    {
        global $name; //这里的global并不是设置为全局变量。而是引用
        echo $name."
";  //输出man
    }
   
    function showtwo()
    {
        //global $name;
        //echo $name."
";
        echo $GLOBALS['name']; //超全局变量数组
    }
   
    show();
    showtwo();
?>

$a = "China"; //Variable a $b = "a"; //Variable b $China = "I'm Chinese !"; //Variable China $f = "b"; //Variable f   echo $a."
"; //Output China echo $$a."
"; //Output I'm Chinese --If you want to parse it as a variable variable, you must add an extra $ symbol in front $a = "f"; //Change the name pointed to by the variable (here is the application of variable variables) echo $$a."
"; //Output b after passing the variable f pointed to above $a = "b"; //Same as above 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 has changed the variable to b. The so-called $$a=$b is the changed value of $b echo $b."
"; //Output China echo $$b; //Output I'm Chinese ?> Note: Mutable variables cannot be applied to $this and superglobal variables (the scope of PHP variables is different from other high-level programming languages. See the code)
The code is as follows Copy code
"; //Output abc Echo $abc; //Output def   echo "

"; Function show() { ​​​​ global $name; //global here is not set as a global variable. Instead quote             echo $name."
"; //Output man }   Function showtwo() { ​​​​ //global $name; //echo $name."
";             echo $GLOBALS['name']; //Super global variable array }   show(); Showtwo(); ?>

Variable function:

The code is as follows Copy code
 代码如下 复制代码

function b()
{
echo "这是B";
}
function c($name = "China") //设默认值
{
echo "这是$name";
}

$a = 'b';
$a(); //找值所在的函数
$a = 'c';
$a(); ?>

 

 

         function b()
                                  {
echo "This is B";
         }
         function c($name = "China") //Set default value
                                        {
echo "This is $name";
         }
                                                                               
          $a = 'b';
           $a(); //Function to find the value
           $a = 'c';
          $a(); ?>

 代码如下 复制代码





无标题文档


   
   


       

           
           

           
           

           
           

           
       

   


foreach($_POST as $key=>$value)
        {       
            //print_r($_POST);
            $$key = $value;
        }
        //extract($_POST); //从数组中将变量导入到当前的符号表 --自行查找php手册
        echo $name."
";
        echo $pwd."
";
        echo $tag."
";
    ?>

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 from the array into the current symbol table --Find the PHP manual by yourself
echo $name."
";
echo $pwd."
";
echo $tag."
";
?>

Variable scope .


Variable scope
The scope of a variable is the context in which it is defined (Translator: To put it bluntly, its effective scope). Most PHP variables have only a single scope. This single scope span also includes files introduced by include and require. Example:

The code is as follows Copy code
 代码如下 复制代码

$a = 1;
include "b.inc";
?> 

$a = 1;

include "b.inc";
代码如下 复制代码

$a = 1; /* global scope */

function Test()
{
echo $a; /* reference to local scope variable */
}

Test();
?> 

?>

This variable $a will take effect in the include file b.inc. However, in user-defined functions, a local function scope will be introduced. Any variables used inside a function will be restricted to the local function scope by default. Example:

The code is as follows Copy code

$a = 1; /* global scope */


function Test()

{
代码如下 复制代码

$a = 1;
$b = 2;

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

$b = $a + $b;
}

Sum();
echo $b;
?> 
 

echo $a; /* reference to local scope variable */

}

Test();

?>

This script will produce no output because the echo statement refers to a local version of the variable $a, and it is not assigned a value within this scope. You may notice that PHP's global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. This can cause problems, as someone might carelessly change a global variable. Global variables in PHP must be declared global when used in functions.

The global keyword
 代码如下 复制代码

$a = 1;
$b = 2;

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

Sum();
echo $b;
?> 
 

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". Global variables $a and $b are declared in the function, and all reference variables of any variable will point to the global variables. PHP has no limit on the maximum number of global variables that a function can declare. The second way to access variables in the global scope is to use a special PHP custom $GLOBALS array. The previous example can be written as: Example 12-2. Using $GLOBALS instead of global
The code is as follows Copy code
$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 the value variable content. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. The following example shows the use of superglobal variables:


Example 12-3. Example demonstrating superglobal variables and scope

The code is as follows Copy code
 代码如下 复制代码

function test_global()
{
// 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。
global $HTTP_POST_VARS;

print $HTTP_POST_VARS['name'];

// Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。
print $_POST['name'];
}
?> 
 

function test_global()
{
// Most predefined variables are not "super", they require the 'global' keyword to make them available in the local scope of the function.

global $HTTP_POST_VARS;


print $HTTP_POST_VARS['name'];

代码如下 复制代码
function Test ()
{
$a = 0;
echo $a;
$a++;
}
?> 
// Superglobals are valid in any scope, they do not require a 'global' declaration. Superglobals were introduced in PHP 4.1.0.

Print $_POST['name'];

}

?>


Use static variables

Another important feature of variable scope is static variables. Static variables only exist in the local function scope, but their values ​​are not lost when program execution leaves this scope. Take a look at the example below:
 代码如下 复制代码
function Test()
{
static $a = 0;
echo $a;
$a++;
}
?> 
 


Example 12-4. Demonstrates the need for static variables

The code is as follows Copy code
function Test ()

{

$a = 0;
echo $a;

$a++;
代码如下 复制代码

function Test()
{
static $count = 0;

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

} ?> This function is not very useful because it sets the value of $a to 0 and prints "0" every time it is called. $a++, which increments a variable by one, has no effect because the variable $a no longer exists once this function exits. To write a counting function that does not lose the current count value, define the variable $a as static: Example 12-5. Example 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 will output the value of $a and increment it by one. Static variables also provide a way to deal with recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely. You must ensure that there are adequate ways to terminate recursion. Consider this simple function that recursively counts to 10, using the 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 as in the above example. Assigning it with the result of an expression in a declaration will result in a parsing error.


Example 12-7. Declare static variables

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The code is as follows
 代码如下 复制代码

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

Copy code

function foo(){
static $int = 0; // correct

static $int = 1+2; // wrong (as it is an expression)
代码如下 复制代码

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

static $int = sqrt(121); // wrong (as it is an expression too)

$int++;

echo $int;

}

?>

 代码如下 复制代码

function &get_instance_ref() {
static $obj;

echo "Static object: ";
var_dump($obj);
if (!isset($obj)) {
// 将一个引用赋值给静态变量
$obj = &new stdclass;
}
$obj->property++;
   return $obj;
}

function &get_instance_noref() {
   static $obj;

   echo "Static object: ";
   var_dump($obj);
   if (!isset($obj)) {
   // 将一个对象赋值给静态变量
   $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();
?> 

References to global and static variables In the first generation of the Zend engine, which drives PHP4, static and global definitions of variables are implemented in the form of references. For example, a true global variable imported with the global statement inside a function scope actually establishes a reference to the global variable. This can lead to unexpected behavior, as the following example demonstrates:
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); ?>
Executing the above example will result in the following output: NULLobject(stdClass)(0) {} Similar behavior also applies to static statements. References are not stored statically:
The code is as follows Copy code
function &get_instance_ref() {<🎜> static $obj;<🎜> <🎜> echo "Static object: ";<🎜> var_dump($obj);<🎜> if (!isset($obj)) {<🎜> //Assign 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)) { //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 above example will result in the following output: Static object: NULLStatic object: NULLStatic object: NULLStatic object: object(stdClass)(1) { ["property"]=> int(1)} The above example demonstrates that when a reference is assigned to a static variable, its value is not remembered the second time the &get_instance_ref() function is called http://www.bkjia.com/PHPjc/628777.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628777.htmlTechArticleVariables are an essential thing in PHP programming. Variables in PHP are divided into global variables and private variables. Variables, let me share some of my understanding and usage of PHP variables. You can refer to them...