function Application of PHP

Source: Internet
Author: User

1. All variables

A global variable, also known as an external variable, is defined outside the function and is scoped to the end of the program file, starting at the definition of the variable. Unlike other programming languages, global variables are not automatically set to be available. In PHP, because a function can be treated as a separate program fragment, the local variable overrides the visibility of the global variable, so the global variable cannot be called directly in the function. To use global variables in a function, you must define the target variable with the global keyword to tell the function body that this variable is a global variable. As shown below:

<?php

$one = 200;

$two = 100;

Function Demo () {

echo "Operation result:". ($one + $two). "      <br> "; The equivalent of a new declaration within the function and does not have an initial value of two variables, the result output: 0

Global $one, $two;

echo "Operation result is:". ($one + $two). "      <br> "; Using a global variable declared outside the function, output: 300

}

Using global variables in a function in addition to using the keyword Global, the second method of accessing variables globally is to use a special PHP custom $globals array. The previous example could be written using $globals instead of global. As shown below:

<?php

$one = 200;

$two = 100;

Function Demo () {

$GLOBALS [' one '] = $GLOBALS [' one '] + $GLOBALS [' one '];

}

Demo ();

Echo $two; Output 300, indicating that global variables are accessed to re-assigned values

In the $globals array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the contents of the variable. $GLOBALS exists globally because $globals is a super global variable.

function Application of 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.