Methods for variables outside of PHP calling functions

Source: Internet
Author: User
According to the general program of thinking, the variables outside the function should be considered as global variables, if it is a global variable, then call in the function is completely no problem. This article is mainly to share with you the PHP call function outside the variable method, I hope to help everyone.

It seems that PHP and our traditional thinking a bit of a problem, then the global variables in PHP, I deliberately write code to try.

1. Define the direct output externally with global:

Global $mytext; $mytext = "Nihao"; function Chao_echo () {echo $mytext;} Chao_echo ();

Result: no output.

2. Output with Globals array:

Global $mytext; $mytext = "Nihao"; function Chao_echo () {echo $GLOBALS [' mytext '];} Chao_echo ();

Result: the output is normal.

3. Declare variables outside the function globally within the function:

$mytext = "Nihao", function Chao_echo () {global $mytext; echo $mytext; Echo $GLOBALS [' mytext '];}

Chao_echo ();
Result: direct output or with Globals global array output is OK.


4. Pass the function external variables in parameters:

$mytext = "Nihao"; function Chao_echo ($mytext) {echo $mytext;} Chao_echo ($mytext);

Result: can be output.

To summarize, in PHP, there are three ways to refer to variables outside the function in a function:

1. Outside the function global declaration, the function uses the $globals array reference.

2. function within the global declaration, function within the $globals array or direct reference.

3. A parameter is passed when the function is called.

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.