PHP variable scopes: curly braces, global, and closures

Source: Internet
Author: User
Tags execution include php form php script require

The scope of a variable is a scope of the variable, in which the variable is visible, that is, the area of the code that can access the variable, and, conversely, if it is not within that scope, the variable is not visible and cannot be invoked. (Global variables can see the scope as the entire program)

Braces

Many languages use curly braces as the scoping line, and only the curly braces of a function in PHP form a new scope.

<?php

if (True) {

$a = ' var a ';

04}

05

Var_dump ($a);

07

for ($i = 0; $i < 1; $i + +) {

$b = ' var b ';

for ($i = 0; $i < 1; $i + +) {

One $c = ' var c ';

12}

Var_dump ($c);

14}

15

Var_dump ($b);

Var_dump ($c);

?>

The results of the operation are:

1 string (5) "Var a" string (5) "Var C" string (5) "Var B" string (5) "Var C"

Visible if and for curly braces do not constitute a new scope.

and functions:

1 <?php

2 function test () {

3 $test = ' var test ';

4}

5

6 test ();

7 Var_dump ($test);

8?>

The result:

1 NULL

Global keyword

PHP is executed in a. php script, in the execution of a. php script, and can include and require other PHP scripts in the execution process.

executed. PHP scripts share a global domain (global scope) with Include/require incoming scripts.

The global keyword, regardless of the layer, is referenced as a variable of the globals domain.

<?php

$test = ' global test ';

The function A () {

$test = ' Test in a () ';

Function B () {

$test of the global;

Modified Var_dump ($test);

08}

b ();

10}

11

A ();

?>

The results of the execution are:

1 string (one) "Global test"

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.