1. There is no global static variable in PHP
When I was doing .NET development, I could use the following method to cache some data:
view plaincopy to clipboardprint?<p></p><p> public class Test { <br>private static int Count = 0; //该变量在整个应用程序中都有效。 <br>} <br>public class Test{ <br>private static int Count = 0; //该变量在整个应用程序中都有效。 <br>} </p> Copy after login |
PGP is an interpreted language. Although it has the static modifier, its meaning is completely different from that in .NET.
Even if a variable in the class is declared as static, this variable is only valid in the current page-level application domain.
2. Understanding variable scope
Variables declared outside the method cannot be accessed within the method body.
For example:
view plaincopy to clipboardprint?<p></p><p><?php <br>$url = "www.51cto.com"; <br>function _DisplayUrl() { <br>echo $url; <br>} <br>function DisplayUrl() { <br>global $url; <br>echo $url; <br>} <br>_DisplayUrl(); <br>DisplayUrl(); <br>?> <br><br>$url = "www.51cto.com"; <br>function _DisplayUrl() { <br>echo $url; <br>} <br>function DisplayUrl(){ <br>global $url; <br>echo $url; <br>} <br>_DisplayUrl(); <br>DisplayUrl(); <br>?> </p> Copy after login |
_DisplayUrl method will not display any results because the variable $url is inaccessible in the method body _DisplayUrl. Just add global before $url, such as the DisplayUrl method.
Global variables defined in the method body can be accessed outside the method:
view plaincopy to clipboardprint?<p></p><p> <?php <br>function _DisplayUrl() { <br>global $myName; <br>$myName='yibin'; <br>} <br>_DisplayUrl(); <br>echo $myName; //output yibin <br>?></p> Copy after login |
What you are reading is "Variable Scope in PHP Website Development"