Local variables and global variables in May 18:php

Source: Internet
Author: User

Local variable: A variable defined inside a function that is scoped to the function definition.
Global variable: A variable defined outside a function whose scope is defined at the end of the file.


In PHP, functions are treated as separate patches, so local variables overwrite global variables, even if they are in local variables and define variables that do not have the same global variables, they are overwritten.
As follows:
$a = 5;
$b = 3;
function T ()
{
echo $a-$b;//Output 0
}
To use global variables directly in a function can be declared through the Global keyword or through a custom $globals array in PHP
function T ()
{
Global $a, $b;
echo $a-$b;
}

function T ()
{
echo $GLOBALS [' a ']-$GLOBALS [' B '];
}


Static variable: Defines a static variable through static, such as:
function test ()
{
Static $t;
$t + +;
return $t;
}
for ($i =0; $i <6; $i + +)
{
echo Test (). " <br/> ";
}
Output 1 2 3 4 5
That is, after the first initialization of a static variable, the value of the variable is always in memory and will not be written off with the function.

Note: If you unset () a static variable in the function, this static variable will be destroyed inside the function. However, when this function is called again, the static variable is restored to the value before it was last destroyed.

Local variables and global variables in May 18:php

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.