Home > Backend Development > PHP Tutorial > Variable scope in PHP website development_PHP tutorial

Variable scope in PHP website development_PHP tutorial

WBOY
Release: 2016-07-13 17:18:54
Original
995 people have browsed it

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
The

_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"

  1. PHP Developer: Have you GLAMMP?
  2. 10 common PHP function codes
  3. Ideas and examples of file uploading in PHP

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/589158.htmlTechArticle1. There is no global static variable in PHP. I used to do .NET development. You can use the following method to cache. Some data: view plaincopy to clipboardprint? public class Test { private...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template