PHP variable scope (curly braces, global, closures)

Source: Internet
Author: User
Tags null null php form rfc variable scope

Braces

Many languages use curly braces as scope boundaries, and only the curly braces of functions in PHP form a new scope.

<?phpif (True) {$a = ' var a ';} Var_dump ($a); for ($i = 0; $i < 1; $i + +) {$b = ' var b '; for ($i = 0; $i < 1; $i + +) {$c = ' var c ';} Var_dump ($c);} Var_dump ($b); Var_dump ($c);? >

The operating result is:

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 the function:

<?phpfunction Test () {$test = ' var test ';} Test (); Var_dump ($test);? >

The result is:

Null

Global keyword

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

Executes a. php script that shares a global domain with the script that Include/require comes in.

The global keyword, regardless of the layer, refers to a variable of the world domain.

<?php$test = ' global test '; function A () {$test = ' Test in a () '; function B () {Global $test; Var_dump ($test);} b ();} A ();? >

The execution results are:

String (one) "Global test"

Closed Package

A closure scope is similar to a function where the inner layer accesses the outer variable and the outer layer cannot access the inner variable.

<?phpfunction A () {$test = ' Test in a () '; function B () {var_dump ($test);//$test cannot be accessed $varb = ' Varb in B () ';} b (); Var_dump ($varb); $varb also cannot be accessed by}a ();? >

Execution Result:

NULL NULL

Extended reading:

    • Variable scope:http://www.php.net/manual/en/language.variables.scope.php
    • PHP RFC closures:http://wiki.php.net/rfc/closures

PHP variable scope (curly braces, global, closures)

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.