If you put include in the function, the variable of pregnancy cannot be called.

Source: Internet
Author: User
When I put include into a function, the variable contained cannot be called? 1. phpecho & nbsp; $ a; 2.php$ a & nbsp; aaaaaaaaaaaa; include (1.php); write and execute 2. php can get the output correctly, but below is not 2. phpfunction & nbsp; loadFile ($ filename) {& the variables included in the include statement cannot be called?
1. php

echo $a;


2. php

$a = "aaaaaaaaaaaa";
include("1.php");



In this way, write and execute 2. php to get the output correctly, but below is not possible
2. php

function loadFile($filename){
include $filename;
}
$a = "aaaaaaaaaaaa";
loadFile("1.php");


Why? Put include into the function. the included files cannot reference their variables.
------ Solution --------------------

function loadFile(){
echo $a;
}
$a = "aaaaaaaaaaaa";
loadFile();


You can try it.
------ Solution --------------------
Variable scope issues.

If you include 1.php into the function, the variables declared outside the function cannot work for it. Unless you perform a global operation in the function. Or use $ GLOBALS ['A'] in 1. php to replace $.

In addition, I have a colleague who also likes to write a lot of files and include them everywhere,
I am very resistant to this practice, which causes global variable pollution. it is often difficult to find a variable to declare or declare a variable, for fear of conflict. And the code is messy.

We recommend that you do not use this method. It is recommended that variables be controlled in a local place, which not only improves the performance of php, but also makes the code logic clearer.
------ Solution --------------------
Okay, this is a scope issue.

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.