Many programmers are using
Note: This document is based on the include description, but also applies to require. These two structures are exactly the same except for how to handle include failures: When the include () fails, include () generates a warning and continues to execute, while require () this results in a fatal error. In other words, if you want to stop processing the page when a file is lost, use require (); otherwise, use include ().
PHP include Scope 1, c
- < ?php
- $color = 'green';
- $fruit = 'apple';
- ?>
- < ?php
- function foo()
- {
- global $color;
- include 'vars.php';
- echo "A $color $fruit";
- }
- foo();
- // A green apple
- echo "A $color $fruit";
- // A green
- ?>
From this example, we can see that:
(1) The PHP include scope of the variable containing the file complies with the scope of the included file. That is, use include in the function to include the variables of other files. These variables are in the scope of this function.
(2) The value of $ color can be printed out of the foo () function without violating the rules of (1. That's because the function has declared $ color as a global (although there is no $ color variable outside of the foo () function, the $ color variable is not vars. the $ color variable in php is a new variable that is forcibly declared as "Global". At this time, it is not assigned a value. When it is included in vars. after php, according to the (1) principle, vars. the $ color variable in php automatically has the scope in the function, so its value is the value of the global variable $ color)
PHP include scope 2. Scope of functions and Classes
- < ?php
- class ClassB {
- /**
- * constructor
- */
- public function __construct(){}
- /**
- * destructor
- */
- public function __destruct() {}
- public function printit() {
- echo 'print it in ClassB.<br />';
- }
- }
- function show_func_included() {
- echo 'show_func_included<br/>';
- }
- ?>
- < ?php
- function include_class() {
- include('classb.php');
- }
- include_class();
- $objB = new ClassB();
- $objB->printit();
- // print it in ClassB.
- show_func_included()
- // show_func_included
- ?>
From this example, we can see that:
All functions and classes defined in the contained files have a global scope after they are included.
Conclusion:
1. the PHP include scope of the variable containing the File follows (does not change) The scope of the included file.
2. All functions and classes defined in the contained files have a global scope after they are included.