Home > Article > Backend Development > "php and MySQL Web Development"-Reading Notes 2
15 Understanding Scope
The scope of a variable controls where the variable is visible and available. Different programming languages have different rules for variable scoping. PHP has fairly simple rules:
1 The scope of variables declared inside a function is from the statement in which they are declared to the end of the function. This is called function scope. These variables are called local variables.
<code><span><?php</span><span><span>function</span><span>fun</span><span>()</span> {</span><span>try</span> { <span>$ob</span> = <span>new</span> obj; } <span>catch</span>(<span>Exception</span><span>$e</span>) { <span>echo</span><span>$e</span>->getMessage(); } <span>$ob</span>->g(); <span>//注意:$ob变量并没有出函数作用域</span> }</span></code>
2 The scope of variables declared outside a function is from the statement in which they are declared to the end of the file, not inside the function. This is called global scope. These variables are called global variables.
3 Special super global variables are visible both inside and outside the function. For example, _GET,_POST,_FILE.etc.
4 Using require() and include() does not affect the scope. If these two statements are used inside a function, function scope applies. If it's not inside a function, global scope applies.
5 The keyword global can be used to manually specify that variables defined or used in a word function have global scope.
6 Variables can be deleted manually by calling unset($variable_name). If a variable is deleted, it is no longer in the scope specified by the parameter.
The above has introduced "php and MySQL Web Development"-Reading Notes 2, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.