Blogger Information
Blog 28
fans 0
comment 0
visits 16438
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
变量作用域-2018年04月16日19时51分
植树青年小江同志的博客
Original
537 people have browsed it

变量作用域的概念:每个变量都有一个针对它的作用域,它是指可以在其中访问变量(从而访问它的值)的一个领域。


  1. 全局作用域:函数之外创建,仅在当前脚本除函数之外的地方使用;

  2. 局部作用域:函数内部创建,仅能在函数中使用,外部无法访问;

  3. 静态作用域:函数内部创建,仅能在函数中使用,函数执行完成它的值不丢失;

实例1

<?php
  //声明全局变量
  $str = "我在函数外";
 
  function fun(){
     //定义局部变量
     $str = "我在函数内";
     echo $str."<br/>";
  }
  //调用函数
  fun();
  echo $str;
?>
上面输出结果:
我在函数内
我在函数外

运行实例 »

点击 "运行实例" 按钮查看在线实例

实例2

<?php
 function myfun(){
   //初始化静态变量
   static $num = 0;
   //静态变量加1
   $num += 1;
   echo $num." ";
 } 
 
 function myfun2(){
   $num = 0;
   $num +=1;
   echo $num." ";
 } 
 
 //调用两次myfun
 myfun();
 myfun();
 
 //输出换行
 echo "<br/>";
 myfun2();
 myfun2();
?>
 
上面的运行结果:
1 2
1 1

运行实例 »

点击 "运行实例" 按钮查看在线实例

实例3

<?php
  //声明全局变量$a和$b
  //并为全局变量赋值
  $a  =  1 ;
  $b  =  2 ;
  function  Sum()
 {  
    /*要想在Sum函数内使用全局变量
      必须用global对变量$a和$b进行
      内部声明
    */
    global  $a , $b ;
    $b  =  $a  +  $b ;
 }
 Sum ();
 echo  $b ;
?> 
上面的输出结果:
3

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!