The PHP global variable defines the current page's overall variable implementation explore _php tips

Source: Internet
Author: User

PHP Global variables in practical applications will find that many problems need us to constantly improve the processing. In this article, we give some specific solutions to the problems of PHP global variables.

the role of the 1:php global variable is to define a global variable , but the global variable is not applied to the entire Web site, but is applied to the current page, including all files with include or require

Copy Code code as follows:

$a = 123;

function AA ()
{
Global $a;
If you do not define $a as a global variable
, the body of the function cannot access the $a
echo $a;
}
AA ();

Summary: The PHP global variable defined in the function body can be used outside of the function body, and the global variable defined outside the function body cannot be used in the function body.
Copy Code code as follows:

$glpbal $a; $a = 123; function f () {echo $a;//Error,}

Take another look at the following example
Copy Code code as follows:

function f ()
{
Global $a;
$a = 123;
}
f ();
echo $a; Correct, you can use

2:php global variable Problem resolution:
Question: I've defined some variables ($a) in config.inc.php, in other files, outside of the function include ("config.inc.php"), the function needs to use these variables inside $a, if not declared, echo $ A is not a print out of anything. So declare global $a, but there are a lot of functions and many variables, you can't keep repeating that statement? If there is any good solution, please advise.

Answer1: First define constants in config.inc.php: Define (constant name, constant value), and then require ' config.inc.php ' in other places that need to be used, and then you can use this constant directly in this file.
Answer2: I also have a way to define an array, such as $x[a, $x, so just declare that global $x one.
Answer3: I tried this method of yours, I can't.
Answer4: Change your php.ini file.
Set the PHP global variable to ON

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.