原文: https://phppot.com/php/variable-scope-in-php/

Last modified on March 24th, 2017 by Vincy.

-------------------------------------------------------

variable scope is known as its boundary within which it can be visible or accessed from code. In other words, it is the context within which a variable is defined. There are only two scopes available in PHP namely local and global scopes.

  1. Local variables (local scope)
  2. Global variables (special global scope)
  3. Static variables (local scope)
  4. Function parameters (local scope)

When a variable is accessed outside its scope it will cause PHP error Undefined Variable.

1. Local Scope Variables

A local scope is a restricted boundary of a variable within which code block it is declared. That block can be a function, class or any conditional span. The variable within this limited local scope is known as the local variable of that specific code block.

The following code block shows a PHP function. We have declared a variable $count inside this function. This variable is said to be a local variable of this function and it is in the local scope of the function block.

<?php
function calculate_count() {
$count = 5;
//will print 5; the value of local variable
echo $count++;
}
?>

Local variables will be destroyed once the end of the code block is reached. Hence the same named variables can be declared within different local scopes.

2. Global Scope Variables

As its name, the global scope provides widespread access to the variable declared in this scope. Variables in global scope can be accessed from anywhere from outside a function or class independent of its boundary.

PHP global variables can be defined by using global keyword. If we want to use global variables inside a function, we have to prefix the global keyword with the variable. The following code shows a code block to learn how to use the global keyword with a PHP variable to declared it as a global variable.

<?php
$count = 0;
function calculate_count() {
global $count;
// will print 0 and increment global variable
echo $count++ . "<br/>";
}
calculate_count();
echo $count;
?>

PHP has a predefined superglobal variable called $GLOBALS. It is an associative array with the name of the variable as key and value as the array element. We can use this array variable to add an array of PHP variables in a global scope.

Let us change the above example with the global keyword by using $GLOBALS superglobal to access the variable in global scope.

<?php
$count = 0;
function calculate_count() {
// will print 0 and increment global variable declared outside function
echo $GLOBALS["count"]++ . "<br/>";
}
calculate_count();
echo $count;
?>

3. Static Variables (local scope)

A static variable is again a variable with local scope. But the difference with the regular local variable is that it is not destroyed outside the scope boundary. A variable can be defined by using the ‘static’ keyword inside a function.

A static variable does not lose its value when the program execution goes past the scope boundary. But it can be accessed only within that boundary. Let me demonstrate it using the following example code,

<?php
function counter()
{
static $count = 0;
echo $count;
$count++;
}
?>

The above counter function has the static variable ‘count’ declared within its local scope. When the function execution is complete, the static count variable still retains its value for further computation. Every time the counter function is called, the value of count is incremented. The count value is initialized only once on the first call.

4. Function Parameters (Local Scope)

Function parameters (arguments) are local variables defined within the local scope of the function on which it is used as the argument.

Scope and File Includes

The boundary of file includes does not demarcate the scope of variables. The scope of a variable is only governed by the function block and not based on the file include. A variable can be declared in a PHP file and used in another file by using ‘include’ or ‘require’ that file.

Function Inside Function or Class

Remember that the scope in PHP is governed by a function block. Any new function declared anywhere starts a new scope. If an anonymous function is defined inside another function, the anonymous function has its own local scope.

<?php
function foo() {
$fruit = 'apple'; $bar = function () {
// $fruit cannot be accessed inside here
$animal = 'lion';
}; // $animal cannot be accessed outside here
}
?>

In the above example code, $fruit variable is restricted to the outer function and its scope does not span inside the anonymous inner function. The same way, $animal which is declared inside is not accessible in the outer function as its scope boundary is restricted to the inner function.

General Note:

Whenever you want to use a variable in a different scope, the way in and way out is by passing as an argument. Do not use global scoped variable for such trivial use cases.

This PHP code tutorial was published on April 12, 2013.

PHP Variable Scope的更多相关文章

  1. [Ruby] Ruby Variable Scope

    Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, lo ...

  2. [翻译] Tensorflow中name scope和variable scope的区别是什么

    翻译自:https://stackoverflow.com/questions/35919020/whats-the-difference-of-name-scope-and-a-variable-s ...

  3. [TensorBoard] Name & Variable scope

    TF有两个scope, 一个是name_scope一个是variable_scope 第一个程序: with tf.name_scope("hello") as name_scop ...

  4. tensorflow变量作用域(variable scope)

    举例说明 TensorFlow中的变量一般就是模型的参数.当模型复杂的时候共享变量会无比复杂. 官网给了一个case,当创建两层卷积的过滤器时,每输入一次图片就会创建一次过滤器对应的变量,但是我们希望 ...

  5. tensorflow variable scope 变量命名空间和变量共享

    import tensorflow as tf def f(): var = tf.Variable(initial_value=tf.random_normal(shape=[2])) return ...

  6. Python中变量的作用域(variable scope)

    http://www.crifan.com/summary_python_variable_effective_scope/ 解释python中变量的作用域 示例: 1.代码版 #!/usr/bin/ ...

  7. JavaScript变量作用域(Variable Scope)和闭包(closure)的基础知识

    在这篇文章中,我会试图讲解JavaScript变量的作用域和声明提升,以及许多隐隐藏的陷阱.为了确保我们不会碰到不可预见的问题,我们必须真正理解这些概念. 基本定义 作用范围是个“木桶”,里面装着变量 ...

  8. Python Variable Scope

    Python中的变量的作用域有时会让像我这样的初学者很头疼. 其实只需要掌握以下两点: 1. Python能够改变变量作用域的代码段是def.class.lamda;    而if/elif/else ...

  9. python variable scope 变量作用域

    python 中变量的作用域经常让我感到很迷 In Python, on the other hand, variables declared in if-statements, for-loop b ...

随机推荐

  1. [水煮 ASP.NET Web API2 方法论](1-1)在MVC 应用程序中添加 ASP.NET Web API

    问题 怎么样将 Asp.Net Web Api 加入到现有的 Asp.Net MVC 项目中 解决方案 在 Visual Studio 2012 中就已经把 Asp.Net Web Api 自动地整合 ...

  2. 如何实现electron多页面间通信

    如何实现electron多页面间通信 1,业务需求: 总共有两个页面,页面A显示数据,页面B处理数据,主线程Main 2,实现的技术方案: 在主线程中打开页面A和B,B页面不进行显示,主要负责处理从A ...

  3. 远程连接服务器上的MySQL

    crt.navicat.Linux系统.MySQL 远程连接上Linux系统,确保Linux系统已经安装上了MySQL数据库.登陆数据库.mysql -uroot -p(密码). 创建用户用来远程连接 ...

  4. 数据库的主从复制常用Xshell命令

    mysql配置 1.设置数据库用户名和密码 mysqladmin -u root password "root" 2.打开3306端口号 iptables -I INPUT -p ...

  5. 【转载】LinearLayout 源码分析

    原文地址:https://github.com/razerdp/AndroidSourceAnalysis/blob/master/LinearLayout/android_widget_Linear ...

  6. 【C语言期末实训】学生学籍管理系统

    目录: 一,设计要求 ,总体要求: ,具体功能: 二,设计框架 三,程序代码 ,声明函数和头文件 ,声明结构体 ,声明全局变量 ,主体启动函数 ,主菜单函数 ,创建学生档案函数 ,编辑学生档案函数 , ...

  7. java Integer parseInt()

    先来一段代码,代码很简单的,如下: public static void main(String[] args) { Integer a = Integer.parseInt("3" ...

  8. Luogu P2016 战略游戏(树形DP)

    题解 设\(f[u][0/1/2]\)表示当前节点\(u\),放或不放(\(0/1\))时其子树满足题目要求的最小代价,\(2\)表示\(0/1\)中的最小值. 则有: \[ f[u][0]=\sum ...

  9. 洛谷——P2784 化学1(chem1)- 化学合成

    P2784 化学1(chem1)- 化学合成 题目背景 蒟蒻HansBug在化学考场上,挠了无数次的头,可脑子里还是一片空白. 题目描述 眼下出现在蒟蒻HansBug面前的是一个化学合成题,据他所知, ...

  10. 【剑指offer】9、斐波拉契数列

    面试题9.斐波拉契数列 题目: 输入整数n,求斐波拉契数列第n个数. 思路: 一.递归式算法: 利用f(n) = f(n-1) + f(n-2)的特性来进行递归,代码如下: 代码: long long ...