변수 유효영역

변수의 유효영역은 변수가 정의된 환경을 말한다. 대부분의 경우 모든 PHP 변수는 한군데의 유효영역만을 갖는다. 이 한군데의 유효영역은 include되거나 require된 파일로도 확장된다. 예를 들면:

<?php
$a 
1;
include 
'b.inc';
?>

위 예제코드에서는 include된 b.inc 스크립트안에서도 $a 변수가 사용가능하다. 하지만, 사용자-선언 함수에서는 로컬 함수 유효영역이 적용된다. 함수내에서 사용되는 모든 변수는 기본값으로 로컬 변수 유효영역 안으로 제한된다. 예를 들면:

<?php
$a 
1/* global scope */ 

function test()

    echo 
$a/* reference to local scope variable */ 


test();
?>

위 스크립트에서 echo문이 $a의 로컬 버전을 참조하고, 이 영역 안에서 값을 지정되지 않았기 때문에 아무것도 출력되지 않는다. C에서 전역변수는 특별히 로컬 선언으로 덮어쓰지 않는이상은 자동적으로 함수안에서 사용가능하다는 점에서 C 언어와 약간 차이가 있다는 것에 주의해야 할것이다. 이런 생각으로 부주의하게 전역변수를 변경하려한다면 문제가 될것이다. PHP에서 전역변수가 함수내에서 계속적으로 사용이 된다면 함수안에서 global로 선언해야 합니다.

global 키워드

우선, global의 사용 예제입니다:

Example #1 global 사용하기

<?php
$a 
1;
$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;


Sum();
echo 
$b;
?>

위 스크립느는 "3"를 출력할것이다. $a$b를 함수내에서 global로 선언함으로써, 각 변수에 대한 모든 참조는 전역 버전으로 참조될것이다. 함순에서 조작되는 전역변수의 수는 제한이 없다.

전역 유효영역의 변수에 접근할수 있는 두번째 방법이 특별 PHP-선언 $GLOBALS 배열을 사용하는 것이다. 이전 예제코드는 다음과 같이 다시 작성할 수 있습니다:

Example #2 global 대신 $GLOBALS 사용하기

<?php
$a 
1;
$b 2;

function 
Sum()
{
    
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];


Sum();
echo 
$b;
?>

$GLOBALS 배열은 전역변수명이 key가 되는 연관배열이고 배열의 원소 값이 그 변수의 내용이 된다. $GLOBALS이 어떻게 모든 유효영역에서 존재하는지 주의하라. 이유는 $GLOBALS이 슈퍼전역변수이기 때문이다. 아래에 슈퍼전역변수의 파워를 설명하는 예제코드를 보였다:

Example #3 자동 전역과 영역을 보여주는 예제

<?php
function test_global()
{
    
// 대부분의 예약 변수는 "자동 전역"이 아니기에,
    // 함수 내부 영역에서 사용하려면 'global'이 필요합니다.
    
global $HTTP_POST_VARS;

    echo 
$HTTP_POST_VARS['name'];
    
    
// 자동 전역은 어떠한 영역에서도 사용할 수 있고,
    // 'global'이 필요하지 않습니다. 자동 전역은
    // PHP 4.1.0부터 사용할 수 있고, HTTP_POST_VARS는
    // 배제되었습니다.
    
echo $_POST['name'];
}
?>

정적 변수 사용하기

변수 유효영역의 또 다른 중요한 기능이 static 변수이다. 정적(static) 변수는 로컬 함수 영역에서만 존재한다. 그러나 프로그램이 그 영역을 떠나지 않으면 그 값을 잃지 않는다. 다음 예제를 생각해 봅시다:

Example #4 정적 변수의 필요성을 보여주는 예제

<?php
function test()
{
    
$a 0;
    echo 
$a;
    
$a++;
}
?>

이 함수는 매번 호출될때마다 $a0으로 설정하고 "0"를 출력한다. $a++ 는 변수를 증가시키지만 함수에서 빠져나가면 $a 변수는 사라지게되므로 아무 가치가 없다. 현재 카운트 값을 잃지 않는 유용한 카운트 함수를 만들려면, $a 변수를 static으로 선언한다.

Example #5 정적 변수의 사용 예제

<?php
function test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
?>

처음 함수를 호출할 때만 $a가 초기화 되고, test() 함수가 호출될때마다 $a 값을 출력하고 그 값이 증가합니다.

정적 변수는 또한 재귀함수를 다루는 한 방법을 제공한다. 재귀함수는 자기 자신을 호출하는 함수를 말한다. 재귀함수는 무한히 실행될수 있기 때문에 재귀함수를 작성할때는 주의가 필요하다. 재귀를 벗어나는 방법을 반드시 갖고 있어야 한다. 다음과 같은 단순 재귀함수는 10까지 카운트한다. 정적 변수 $count는 멈춰야 할 때는 안다.

Example #6 재귀 함수에서 정적 변수

<?php
function test()
{
    static 
$count 0;

    
$count++;
    echo 
$count;
    if (
$count 10) {
        
test();
    }
    
$count--;
}
?>

Note:

정적 변수는 위 예제처럼 선언해야 합니다. 이 변수에 표현식의 결과를 할당하려 할 경우는 해석 오류를 발생합니다.

Example #7 정적 변수 선언하기

<?php
function foo() {
    static 
$int 0;          // 적합
    
static $int 1+2;        // 오류 (표현식이기에)
    
static $int sqrt(121);  // 오류 (역시 표현식이기에)

    
$int++;
    echo 
$int;
}
?>

전역 변수와 정적 변수의 참조

PHP 4를 작동하는 Zend Engine 1은 staticglobal참조를 통한 변수 변경자로 구현합니다. 예를 들어, 실제 전역 변수를 global 키워드를 사용하여 함수 영역 내부로 가져올 경우, 그 전역 변수의 참조를 생성합니다. 이로 인해 다음 예제에서 처럼 원하지 않은 동작을 할 수 있습니다:

<?php
function test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

위 예제코드를 실행하면 다음과 같은 결과가 유도된다.


NULL
object(stdClass)(0) {
}

이와 비슷한 동작이 static 절에서도 발생한다. 참조가 정적으로 저장되지 않는것이다:

<?php
function &get_instance_ref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign a reference to the static variable
        
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign the object to the static variable
        
$obj = new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

$obj1 get_instance_ref();
$still_obj1 get_instance_ref();
echo 
"\n";
$obj2 get_instance_noref();
$still_obj2 get_instance_noref();
?>

위 예제코드를 실행하면 다음과 같은 결과가 유도된다.


Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

위 예제 코드는 정적 변수에 대한 참조를 지정할때, &get_instance_ref()함수가 두번째로 호출되는 때에 기억되지 않는다는 것을 보여준다.

add a note add a note

User Contributed Notes 9 notes

up
208
dodothedreamer at gmail dot com
13 years ago
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
     if(
$j == 1)
       
$a = 4;
}
echo
$a;
?>

Would print 4.
up
174
warhog at warhog dot net
19 years ago
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.

<?php

class sample_class
{
  public function
func_having_static_var($x = NULL)
  {
    static
$var = 0;
    if (
$x === NULL)
    { return
$var; }
   
$var = $x;
  }
}

$a = new sample_class();
$b = new sample_class();

echo
$a->func_having_static_var()."\n";
echo
$b->func_having_static_var()."\n";
// this will output (as expected):
//  0
//  0

$a->func_having_static_var(3);

echo
$a->func_having_static_var()."\n";
echo
$b->func_having_static_var()."\n";
// this will output:
//  3
//  3
// maybe you expected:
//  3
//  0

?>

One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.

Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:

<?php
class sample_class
{ protected $var = 0;
  function
func($x = NULL)
  {
$this->var = $x; }
}
?>

I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
up
29
andrew at planetubh dot com
15 years ago
Took me longer than I expected to figure this out, and thought others might find it useful.

I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).

Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.

Most places (including here) seem to address this issue by something such as:
<?php
//declare this before include
global $myVar;
//or declare this inside the include file
$nowglobal = $GLOBALS['myVar'];
?>

But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)

My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)

<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>

Thus, complete code looks something like the following (very basic model):

<?php
function safeinclude($filename)
{
   
//This line takes all the global variables, and sets their scope within the function:
   
foreach ($GLOBALS as $key => $val) { global $$key; }
   
/* Pre-Processing here: validate filename input, determine full path
        of file, check that file exists, etc. This is obviously not
        necessary, but steps I found useful. */
   
if ($exists==true) { include("$file"); }
    return
$exists;
}
?>

In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course.  In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).

Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().
up
17
larax at o2 dot pl
18 years ago
About more complex situation using global variables..

Let's say we have two files:
a.php
<?php
   
function a() {
        include(
"b.php");
    }
   
a();
?>

b.php
<?php
    $b
= "something";
    function
b() {
        global
$b;
       
$b = "something new";
    }
   
b();
    echo
$b;
?>

You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:

global $b;
$b = "something";
up
16
Michael Bailey (jinxidoru at byu dot net)
20 years ago
Static variables do not hold through inheritance.  Let class A have a function Z with a static variable.  Let class B extend class A in which function Z is not overwritten.  Two static variables will be created, one for class A and one for class B.

Look at this example:

<?php
class A {
    function
Z() {
        static
$count = 0;       
       
printf("%s: %d\n", get_class($this), ++$count);
    }
}

class
B extends A {}

$a = new A();
$b = new B();
$a->Z();
$a->Z();
$b->Z();
$a->Z();
?>

This code returns:

A: 1
A: 2
B: 1
A: 3

As you can see, class A and B are using different static variables even though the same function was being used.
up
5
gried at NOSPAM dot nsys dot by
8 years ago
In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:

<?php

error_reporting
(E_ALL);

$GLOB = 0;

function
test_references() {
    global
$GLOB; // get reference to global variable using keyword global, at this point local variable $GLOB points to same address as global variable $GLOB
   
$test = 1; // declare some local var
   
$GLOBALS['GLOB'] = &$test; // make global variable reference to this local variable using superglobal array, at this point global variable $GLOB points to new memory address, same as local variable $test

   
$GLOB = 2; // set new value to global variable via earlier set local representation, write to old address

   
echo "Value of global variable (via local representation set by keyword global): $GLOB <hr>";
   
// check global variable via local representation => 2 (OK, got value that was just written to it, cause old address was used to get value)

   
echo "Value of global variable (via superglobal array GLOBALS): $GLOBALS[GLOB] <hr>";
   
// check global variable using superglobal array => 1 (got value of local variable $test, new address was used)
   
   
echo "Value ol local variable \$test: $test <hr>";
   
// check local variable that was linked with global using superglobal array => 1 (its value was not affected)
   
   
global $GLOB; // update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $test
   
echo "Value of global variable (via updated local representation set by keyword global): $GLOB <hr>";
   
// check global variable via local representation => 1 (also value of local variable $test, new address was used)
}

test_references();
echo
"Value of global variable outside of function: $GLOB <hr>";
// check global variable outside function => 1 (equal to value of local variable $test from function, global variable also points to new address)
?>
up
3
jameslee at cs dot nmt dot edu
19 years ago
It should be noted that a static variable inside a method is static across all instances of that class, i.e., all objects of that class share the same static variable.  For example the code:

<?php
class test {
    function
z() {
        static
$n = 0;
       
$n++;
        return
$n;
    }
}

$a =& new test();
$b =& new test();
print
$a->z();  // prints 1, as it should
print $b->z();  // prints 2 because $a and $b have the same $n
?>

somewhat unexpectedly prints:
1
2
up
3
dexen dot devries at gmail dot com
7 years ago
If you have a static variable in a method of a class, all DIRECT instances of that class share that one static variable.

However if you create a derived class, all DIRECT instances of that derived class will share one, but DISTINCT, copy of that static variable in method.

To put it the other way around, a static variable in a method is bound to a class (not to instance). Each subclass has own copy of that variable, to be shared among its instances.

To put it yet another way around, when you create a derived class, it 'seems  to' create a copy of methods from the base class, and thusly create copy of the static variables in those methods.

Tested with PHP 7.0.16.

<?php

require 'libs.php';
require
'setup.php';

class
Base {
    function
test($delta = 0) {
        static
$v = 0;
       
$v += $delta;
        return
$v;
    }
}

class
Derived extends Base {}

$base1 = new Base();
$base2 = new Base();
$derived1 = new Derived();
$derived2 = new Derived();

$base1->test(3);
$base2->test(4);
$derived1->test(5);
$derived2->test(6);

var_dump([ $base1->test(), $base2->test(), $derived1->test(), $derived2->test() ]);

# => array(4) { [0]=> int(7) [1]=> int(7) [2]=> int(11) [3]=> int(11) }

# $base1 and $base2 share one copy of static variable $v
# derived1 and $derived2 share another copy of static variable $v
up
0
randallfstewart at gmail dot com
10 months ago
Note that the global keyword inside a function does (at least) 2 different things:

1) As stated in the manual, it allows the function to use *the global version* of the variable: "...all references to either variable will refer to *the global version*."  [emphasis mine]

2) As not stated in the manual, if the variable does not already exist in the global scope, it is created in the global scope.

For example, in the code below, the variable $A is available in the global scope (after functionA is called), even though it was never declared in the global scope:

<?php

echo "<p>This is A before functionA is called: {$A}.</p>";

functionA();

function
functionA(){
global
$A;
$A = "Declared as global inside functionA";
// end fcn callGlobal

echo "<p>This is A after functionA is called: {$A}</p>";
?>

Results:
Notice: Undefined variable: A in /home/essma/public_html/global_test.php on line 3

This is A before functionA is called: .

This is A after functionA is called: Declared as global inside functionA
To Top