PHPのお勉強!

PHP TOP

変数のスコープ

変数のスコープは、その変数が定義されたコンテキストです。ほとんどの PHP 変数は、スコープを1つだけ有しています。このスコープの範囲は、 includeやrequireにより読みこまれたファイルも含みます。例えば、

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

この例で、変数$aはインクルードされた b.inc スクリプトの中でも利用可能です。しかし、 ユーザー定義の関数の中では変数の有効範囲はローカル関数の中となりま す。関数の中で使用された変数はデフォルトで有効範囲が関数内部に制限 されます。例えば、

<?php
$a 
1/* グローバルスコープ */ 

function test()

    echo 
$a/* ローカルスコープ変数の参照 */ 


test();
?>

このスクリプトは、出力を全く行いません。これは、echo 命令がローカ ル版の $a 変数を参照しているにもかかわらず、こ のスコープでは値が代入されていないからです。この動作は、特にローカ ルな定義で上書きしない限りグローバル変数が自動的に関数で使用可能で ある C 言語と少々異なっていると気がつかれるかもしれません。C言語の ような場合、グローバル変数を不注意で変更してしまうという問題を生じ る可能性があります。PHP では、グローバル変数は、関数の内部で使用す る場合、関数の内部でグローバルとして宣言する必要があります。

global キーワード

まず、globalの使用例を示します。

例1 global の使用

<?php
$a 
1;
$b 2;

function 
Sum() 
{
    global 
$a$b;

    
$b $a $b;


Sum();
echo 
$b;
?>

上のスクリプトは、3 を出力します。関数の内部で $a$b をグローバル宣言を行うことにより、両変数への参照は、グローバル変数 の方を参照することになります。ある関数により操作できるグローバル変 数の数は無制限です。

グローバルスコープから変数をアクセスする2番目の方法は、PHPが定義す る配列$GLOBALSを使用することです。先の例は、次 のように書き換えることができます。

例2 globalのかわりに$GLOBALSを使用する

<?php
$a 
1;
$b 2;

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


Sum();
echo 
$b;
?>

配列$GLOBALSは連想配列であり、グローバル変数の 名前がキー、その変数の内容が配列要素の値となっています。 $GLOBALSスーパーグローバル であるため、$GLOBALSは全てのスコープに存在します。 以下にスーパーグローバルの効果を示す例を示します。

例3 スーパーグローバルとスコープの例

<?php
function test_superglobal()
{
    echo 
$_POST['name'];
}
?>

注意:

global キーワードを関数の外部で使ってもエラーにはなりません。 そのファイルが関数の内部からインクルードされたときに使うことができます。

静的変数の使用

変数のスコープに関する別の重要な機能は、静的 (static) 変数です。静的変数はローカル関数スコープのみに 存在しますが、プログラム実行がこのスコープの外で行われるようになっ てもその値を失わないません。次の例を見てください。

例4 静的変数が必要な場面の例

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

この関数は、コールされる度に$a0にセットし、0 を出力するのでほとん ど役にたちません。変数を1増やす $a++ は、関数から外に出ると変数 $aが消えてしまうために目的を達成しません。現在 のカウントの追跡ができるようにカウント関数を使用できるようにするた めには、変数$aをstaticとして宣言します。

例5 静的変数の使用例

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

こうすると、$a は関数が最初にコールされたときにのみ初期化され、 test() 関数がコールされるたびに $a の値を出力してその値を増加させます。

static変数は、再帰関数を実現する1つの手段としても使用されます。再帰 関数は、自分自身をコールする関数です。再帰関数を書くときには、無限 に再帰を行う可能性があるため、注意する必要があります。適当な方法に より再帰を確実に終了させる必要があります。次の簡単な関数は、中止す るタイミングを知るためにstatic変数$countを用いて、 10 回まで再帰を行います。

例6 再帰関数での静的変数の使用

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

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

注意:

静的変数は、上の例に見られるような方法で宣言されます。 PHP 5.6 以降は、これらの変数に式の結果の値を代入できます。 しかし関数は使えません。関数を使おうとするとパースエラーが発生します。

例7 静的変数の宣言

<?php
function foo(){
    static 
$int 0;          // 正しい
    
static $int 1+2;        // 正しい(ただし、PHP 5.6 以降に限ります)
    
static $int sqrt(121);  // 間違い(関数を使っています)

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

注意:

静的な宣言は、コンパイル時に解決されます。

グローバル変数と静的変数のリファレンス

PHP は、 リファレンス 変数の修正子として static および global を実装しています。 例えば、関数スコープ内にglobal 命令により実際にインポートされた真のグローバル変数は、 実際にグローバル変数へのリファレンスを作成します。 これにより、以下の例が示すように予測できない動作を引き起こす可能性 があります。

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

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

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

上の例の出力は以下となります。

NULL
object(stdClass)#1 (0) {
}

類似の動作がstatic命令にも適用されます。 リファレンスは静的に保存することができません。

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

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

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
$new = new stdclass;
        
// Assign the object to the static variable
        
$obj $new;
    }
    if (!isset(
$obj->property)) {
        
$obj->property 1;
    } else {
        
$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)#3 (1) {
  ["property"]=>
  int(1)
}
+

この例は、static変数にリファレンスを代入した時に &get_instance_ref()関数を2回目に コールした際に保持されていないことを示しています。

add a note add a note

User Contributed Notes 37 notes

up
145
warhog at warhog dot net
14 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
116
dodothedreamer at gmail dot com
8 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
67
HOSSEIN doesn&#39;t want spam at TAKI.IR
10 years ago
Please note for using global variable in child functions:

This won't work correctly...

<?php
function foo(){
   
$f_a = 'a';
   
    function
bar(){
        global
$f_a;
        echo
'"f_a" in BAR is: ' . $f_a . '<br />'// doesn't work, var is empty!
   
}
   
   
bar();
    echo
'"f_a" in FOO is: ' . $f_a . '<br />';
}
?>

This will...

<?php
function foo(){
    global
$f_a;   // <- Notice to this
   
$f_a = 'a';
   
    function
bar(){
        global
$f_a;
        echo
'"f_a" in BAR is: ' . $f_a . '<br />'// work!, var is 'a'
   
}
   
   
bar();
    echo
'"f_a" in FOO is: ' . $f_a . '<br />';
}
?>
up
5
shaman_master at list dot ru
9 months ago
Cycle not create inner scope:
<?php
foreach (range(1, 3) as $step) {
    echo
sprintf('%d: %s  ', $step, isset($a) ? 'yes' : 'no');
    if (! isset(
$a)) {
       
$a = 1;
    }
}
// 1: no 2: yes 3: yes
?>
up
21
Michael Bailey (jinxidoru at byu dot net)
16 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
24
andrew at planetubh dot com
11 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
15
ddarjany at yahoo dot com
12 years ago
Note that if you declare a variable in a function, then set it as global in that function, its value will not be retained outside of that function.  This was tripping me up for a while so I thought it would be worth noting.

<?PHP

foo
();
echo
$a; // echoes nothing

bar();
echo
$b; //echoes "b";

function foo() {
 
$a = "a";
  global
$a;
}

function
bar() {
  global
$b;
 
$b = "b";
}

?>
up
12
dexen dot devries at gmail dot com
3 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
19
larax at o2 dot pl
14 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
7
zweibieren at yahoo dot com
5 years ago
Take to heart this hard-won rule:
        Declare AT THE TOP any variable that is to be global.
        Both at the top of the FILE
        AND at the top of any FUNCTION where it appears.

Why AT THE TOP? So it is sure to be declared before use. Otherwise a non-global version of the variable will be created and your code will fail.

Why at the top of a FUNCTION? Because otherwise the function will refer only to its local version of the variable and your code will fail.

Why at the top of the FILE? Because someday--a day that you cannot now imagine--you will want to "include" the file. And when you do, instances of the variable outside functions will not go in the global scope and your code will fail. (When the "include" is inside a calling function, variables in the included file go into the scope of the calling function.)

Example file where variable $x is used outside and inside functions:
    |<!DOCTYPE html ...>
    |<html xmlns ...>
    |    <?php global $x; ?>
    |<head>
    |    Some html headers
    |    <?php
   
|        $x = 1;
    |        function
bump_x() {
    |            global
$x;
    |           
$x += 1;
    |        }
    |   
?>
    |</head>
    |<body>
    |    More html
    |    <?php echo $x; bump_x(); ?>
    |    Yet more html.
    |</body>
</html>
up
8
danno at wpi dot edu
19 years ago
WARNING!  If you create a local variable in a function and then within that function assign it to a global variable by reference the object will be destroyed when the function exits and the global var will contain NOTHING!  This main sound obvious but it can be quite tricky you have a large script (like a phpgtk-based gui app ;-) ).

example:

<?php
function foo ()
{
   global
$testvar;

  
$localvar = new Object ();
  
$testvar = &$localvar;
}

foo ();
print_r ($testvar);   // produces NOTHING!!!!
?>

hope this helps someone before they lose all their hair
up
11
Anonymous
8 years ago
It will be obvious for most of you: changing value of a static in one instance changes value in all instances.

<?php

   
class example {
        public static
$s = 'unchanged';
       
        public function
set() {
           
$this::$s = 'changed';
        }
    }

   
$o = new example;
   
$p = new example;

   
$o->set();

    print
"$o static: {$o::$i}\n$p static: {$p::$i}";

?>

Output will be:

$o static: changed
$p static: changed
up
6
pogregoire##live.fr
4 years ago
writing : global $var; is exactely the samething that writing : $var =& $GLOBALS['var'];
It creates a reference on $GLOBALS['var'];

<?php
$var
=1;
function
teste_global(){
    global
$var;
    for (
$var=0; $var<5; $var++){

    }
}

teste_global();
var_dump($var);// return : int(5).
?>
up
6
Jonathan Kenigson
6 years ago
Just a note about static properties declared at class level:

class Test_Class {
  static $a = 0;
  public function ReturnVar(){
    return $this->a;
  }
  }
  $b = new Test_Class();
  echo $b->ReturnVar();

Will not output "0"  because $a is declared static. Changing "static" to "public" or "private" will produce the output "0".
up
10
php at keith tyler dot com
9 years ago
Sometimes a variable available in global scope is not accessible via the 'global' keyword or the $GLOBALS superglobal array. I have not been able to replicate it in original code, but it occurs when a script is run under PHPUnit.

PHPUnit provides a variable "$filename" that reflects the name of the file loaded on its command line. This is available in global scope, but not in object scope. For example, the following phpUnit script (call it GlobalScope.php):

<?php
print "Global scope FILENAME [$filename]\n";
class
MyTestClass extends PHPUnit_Framework_TestCase {
  function
testMyTest() {
    global
$filename;
    print
"Method scope global FILENAME [$filename]\n";
    print
"Method scope GLOBALS[FILENAME] [".$GLOBALS["filename"]."]\n";
  }
}
?>

If you run this script via "phpunit GlobalScope.php", you will get:

Global scope FILENAME [/home/ktyler/GlobalScope.php]
PHPUnit 3.4.5 by Sebastian Bergmann.

Method scope global FILENAME []
Method scope GLOBALS[FILENAME] []
.

You have to -- strange as it seems -- do the following:

<?php
$GLOBALS
["filename"]=$filename;
print
"Global scope FILENAME [$filename]\n";
class
MyTestClass extends PHPUnit_Framework_TestCase {
  function
testMyTest() {
    global
$filename;
    print
"Method scope global FILENAME [$filename]\n";
    print
"Method scope GLOBALS[FILENAME] [".$GLOBALS["filename"]."]\n";
  }
}
?>

By doing this, both "global" and $GLOBALS work!

I don't know what it is that PHPUnit does (I know it uses Reflection) that causes a globally available variable to be implicitly unavailable via "global" or $GLOBALS. But there it is.
up
6
Randolpho
16 years ago
More on static variables:

A static variable does not retain it's value after the script's execution. Don't count on it being available from one page request to the next; you'll have to use a database for that.

Second, here's a good pattern to use for declaring a static variable based on some complex logic:

<?php
 
function buildStaticVariable()
  {
     
$foo = null;
     
// some complex expression or set of
      // expressions/statements to build
      // the return variable.
     
return $foo;
  }

  function
functionWhichUsesStaticVar()
  {
      static
$foo = null;
      if(
$foo === null) $foo = buildStaticVariable();
     
// the rest of your code goes here.
 
}
?>

Using such a pattern allows you to separate the code that creates your default static variable value from the function that uses it. Easier to maintain code is good. :)
up
4
kouber at php dot net
15 years ago
If you need all your global variables available in a function, you can use this:

<?php
function foo() {
 
extract($GLOBALS);
 
// here you have all global variables

}
?>
up
5
eduardo dot ferron at zeion dot net
9 years ago
There're times when global variables comes in handy, like universal read only resources you just need to create once in your application and share to the rest of your scripts. But it may become quite hard to track with "variables".
up