變數範圍

變數的範圍即它定義的上下文背景(也就是它的生效範圍)。大部分的 PHP 變數只有一個單獨的範圍。這個單獨的範圍跨度同樣包含了 include 和 require 引入的文件。例如:

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

這裡變數 $a 將會在包含文件 b.inc 中生效。但是,在用戶自定義函式中,一個局部函式範圍將被引入。任何用於函式內部的變數按缺省情況將被限制在局部函式範圍內。例如:

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

function Test()
{
    echo 
$a/* reference to local scope variable */
}

Test();
?>

這個腳本不會有任何輸出,因為 echo 語句引用了一個局部版本的變數 $a,而且在這個範圍內,它並沒有被指派。你可能注意到 PHP 的全局變數和 C 語言有一點點不同,在 C 語言中,全局變數在函式中自動生效,除非被局部變數覆蓋。這可能引起一些問題,有些人可能漫不經心的改變一個全局變數。PHP 中全局變數在函式中使用時必須申明為全局。

global 關鍵字

首先,一個使用 global 的例子:

Example #1 使用 global

<?php
$a 
1;
$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;
}

Sum();
echo 
$b;
?>

以上腳本的輸出將是「3」。在函式中申明了全局變數 $a$b,任何變數的所有引用變數都會指向到全局變數。對於一個函式能夠申明的全局變數的最大個數,PHP 沒有限制。

在全局範圍內訪問變數的第二個辦法,是用特殊的 PHP 自定義 $GLOBALS 數組。前面的例子可以寫成:

Example #2 使用 $GLOBALS 替代 global

<?php
$a 
1;
$b 2;

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

Sum();
echo 
$b;
?>

$GLOBALS 數組中,每一個變數為一個元素,鍵名對應變數名,值對應變數的內容。$GLOBALS 之所以在全局範圍內存在,是因為 $GLOBALS 是一個超全局變數。以下範例顯示了超全局變數的用處:

Example #3 演示超全局變數和作用域的例子

<?php
function test_global()
{
    
// 大多數的預定義變數並不 "super",它們需要用 'global' 關鍵字來使它們在函式的本地區域中有效。
    
global $HTTP_POST_VARS;

    echo 
$HTTP_POST_VARS['name'];

    
// Superglobals 在任何範圍內都有效,它們並不需要 'global' 聲明。Superglobals 是在 PHP 4.1.0 引入的。
    
echo $_POST['name'];
}
?>

使用靜態變數

變數範圍的另一個重要特性是靜態變數(static variable)。靜態變數僅在局部函式域中存在,但當程序執行離開此作用域時,其值並不丟失。看看下面的例子:

Example #4 演示需要靜態變數的例子

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

本函式沒什麼用處,因為每次調用時都會將 $a 的值設為 0 並輸出 "0"。將變數加一的 $a++ 沒有作用,因為一旦退出本函式則變數 $a 就不存在了。要寫一個不會丟失本次計數值的計數函式,要將變數 $a 定義為靜態的:

Example #5 使用靜態變數的例子

<?php
function Test()
{
    static 
$a 0;
    echo 
$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;          // correct
    
static $int 1+2;        // wrong  (as it is an expression)
    
static $int sqrt(121);  // wrong  (as it is an expression too)

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

全局和靜態變數的引用

在 Zend 引擎 1 代,它驅動了 PHP4,對於變數的 staticglobal 定義是以 references 的方式實現的。例如,在一個函式域內部用 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)) {
        
// 將一個引用指派給靜態變數
        
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// 將一個對像指派給靜態變數
        
$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 42 notes

up
152
warhog at warhog dot net
18 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
128
dodothedreamer at gmail dot com
12 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
70
HOSSEIN doesn&#39;t want spam at TAKI.IR
13 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
30
Michael Bailey (jinxidoru at byu dot net)
19 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
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
8
zweibieren at yahoo dot com
8 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
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
11
ddarjany at yahoo dot com
15 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
11
php at keith tyler dot com
13 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
9
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
7
danno at wpi dot edu
22 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
9
Anonymous
11 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
5
pogregoire##live.fr
7 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
3
shaman_master at list dot ru
4 years 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
5
Randolpho
20 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
3
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
4
Jonathan Kenigson
10 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
3
kouber at php dot net
19 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
8
Stephen Dewey
14 years ago
For nested functions:

This is probably obvious to most people, but global always refers to the variable in the global (top level) variable of that name, not just a variable in a higher-level scope. So this will not work:
<?php

// $var1 is not declared in the global scope

function a($var1){

    function
b(){
        global
$var1;
        echo
$var1; // there is no var1 in the global scope so nothing to echo
   
   
}

   
b();
}

a('hello');

?>
up
3
eduardo dot ferron at zeion dot net
13 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
2
moraesdno at gmail dot com
14 years ago
Use the superglobal array $GLOBALS is faster than the global keyword. See:

<?php
//Using the keyword global
$a=1;
$b=2;
function
sum() {
    global
$a, $b;
   
$a += $b;
}

$t = microtime(true);
for(
$i=0; $i<1000; $i++) {
    
sum();
}
echo
microtime(true)-$t;
echo
" -- ".$a."<br>";

//Using the superglobal array
$a=1;
$b=2;
function
sum2() {
   
$GLOBALS['a'] += $GLOBALS['b'];
}

 
$t = microtime(true);
for(
$i=0; $i<1000; $i++) {
    
sum2();
}
echo
microtime(true)-$t;
echo
" -- ".$a."<br>";
?>
up
2
jakub dot lopuszanski at nasza-klasa dot pl
13 years ago
If you use __autoload function to load classes' definitons, beware that "static local variables are resolved at compile time" (whatever it really means) and the order in which autoloads occur may impact the semantic.

For example if you have:
<?php
class Singleton{
  static public function
get_instance(){
     static
$instance = null;
     if(
$instance === null){
       
$instance = new static();
     }
     return
$instance;
  }
}
?>

and two separate files A.php and B.php:
class A extends Singleton{}
class B extends A{}

then depending on the order in which you access those two classes, and consequently, the order in which __autoload includes them, you can get strange results of calling B::get_instance() and A::get_instance().

It seems that static local variables are alocated in as many copies as there are classes that inherit a method at the time of inclusion of parsing Singleton.
up
1
simon dot barotte at gmail dot com
7 years ago
To be vigilant, unlike Java or C++, variables declared inside blocks such as loops (for, while,...) or if's, will also be recognized and accessible outside of the block, the only valid block is the BLOCK function so:

<?php
for($j=0; $j<5; $j++)
{
     if(
$j == 1){
       
$a = 6;
     }
}

echo
$a;
?>

Would print 6.
up
1
info AT SyPlex DOT net
19 years ago
Some times you need to access the same static in more than one function. There is an easy way to solve this problem:

<?php
 
// We need a way to get a reference of our static
 
function &getStatic() {
    static
$staticVar;
    return
$staticVar;
  }

 
// Now we can access the static in any method by using it's reference
 
function fooCount() {
   
$ref2static = & getStatic();
    echo
$ref2static++;
  }

 
fooCount(); // 0
 
fooCount(); // 1
 
fooCount(); // 2
?>
up
-1
admin at shenjinpeng dot cn
2 years ago
<?php

function foo(){
    static
$a= 0;
   
$bar = function(){
        global
$a ;
        return ++
$a;
    };
   
    return
$bar();
}

echo
foo(); // 1
echo foo(); // 2

function foo1(){
   
$bar = function(){
        static
$a = 0;
        return ++
$a;
    };
   
    return
$bar();
}

echo
foo1() ; // 1
echo foo1() ; // 1

function foo2(){
    static
$a = 0;
   
$bar = function() use (&$a){
        return ++
$a;
    };
   
    return
$bar();
}

echo
foo2() ; // 1
echo foo2() ; // 2

function foo3($func){
    static
$a = 0;
    return
$func($a);
}

echo
foo3(fn(&$a) => ++$a ); // 1
echo foo3(fn(&$a) => ++$a ); // 2

?>
up
-1
2505036090 at qq dot com
2 years ago
About assignment of object:
```php
<?php
function aaa() {
    global
$obj;
   
$cl = new stdclass;
   
$obj = &$cl; //  assign By Ref
   
$obj->name = 'jack';
   
$obj = NULL; // the change of $obj leads to the change of $cl
   
var_dump($cl); // output: NULL
}
aaa();
var_dump($obj); // output: NULL

function bbb() {
    global
$obj;
   
$cl = new stdclass;
   
$obj = $cl; // general assignment of object
   
$obj->name = 'jack';
   
$obj = NULL; // the value of $obj changes to NULL, but the value of $cl  is still original;
   
var_dump($cl); //output:  object(stdClass)#2 (1) { ["name"]=> string(4) "jack" }
}
bbb();
var_dump($obj); // output: NULL
?>
```
up
-1
atesin () 6m4i1 ! c0m
3 years ago
i hadn't found info on this so i had to make some tests...

inside a function, when globalling a variable that doesn't exist in the parent scope, it will set to null... i mean...

<?php

function f()
{
  global
$g;
 
var_dump($g); // prints 'NULL' with no log message, means if $g is unset globally then here IS SET to NULL (*)
 
var_dump($l); // prints 'NULL' and logs the 'undefined variable l' notice in this line
 
  // (*) notice until the variable $g IS SET to null here, isset($g) will still return false
  //     because for isset() the var has to be set and not null (see doc for details)...
  //     maybe the only way to find if a variable is actually unset is throught the log warnings
}

var_dump($g); // prints 'NULL' and logs the 'undefined variable g' in this line
var_dump($g); // same as above but in this line, means the variable is still unset
f();

?>

.
knowing this could be useful in a case like mine... consider something like this...

<?php

//--- account.php ---

$user = 'john doe';

//--- main.php ---

function welcome()
{
  global
$user;
  echo
"welcome $user"; // if $user is not set in parent scope it just prints "welcome "

  // the right way afaik
 
if ( isset($user) )
    echo
"welcome $user";
}

if (
login_ok() )
 
incude 'account.php';

welcome();

?>
up
-1
Duke dot Bouvier at NOPSAM dot Gmail dot com
3 years ago
The recursion example has some excess code:

"$count--" is superfluous.
"$count++" can be built into the loop (but be sure to use pre-increment not a post-incremenet

Thus:

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

    echo
$count." ";

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

Though with a static, all you are really doing is creating a loop but with lots of function calls pushed onto the stack.

A great things about recursive functions is that you don't actually have to have any static data.  You simply supply an argument to pass the value (and can use a default value for the argument for your initialisation if desired.)

<?php
function test($count = 1)
{
    echo
$count." ";

    if (
$count < 10) {
       
test(++$count);
    }

}
test()
?>
up
-1
jtunaley at gmail dot com
3 years ago
It's worth noting that block statements without a control structure also don't affect variable scope.

<?php
{
   
$a = 4;
}
echo
$a; // Outputs "4"
up
0
jake dot tunaley at berkeleyit dot com
5 years ago
Beware of using $this in anonymous functions assigned to a static variable.

<?php
class Foo {
    public function
bar() {
        static
$anonymous = null;
        if (
$anonymous === null) {
           
// Expression is not allowed as static initializer workaround
           
$anonymous = function () {
                return
$this;
            };
        }
        return
$anonymous();
    }
}

$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // Also true
?>

In a static anonymous function, $this will be the value of whatever object instance that method was called on first.

To get the behaviour you're probably expecting, you need to pass the $this context into the function.

<?php
class Foo {
    public function
bar() {
        static
$anonymous = null;
        if (
$anonymous === null) {
           
// Expression is not allowed as static initializer workaround
           
$anonymous = function (self $thisObj) {
                return
$thisObj;
            };
        }
        return
$anonymous($this);
    }
}

$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // False
?>
up
1
Anonymous
16 years ago
I was pondering a little something regarding caching classes within a function in order to prevent the need to initiate them multiple times and not clutter the caching function's class properties with more values.

I came here because I remembered something about references being lost. So I made a test to see if I could pull what I wanted to off anyway. Here's and example of how to get around the references lost issue. I hope it is helpful to someone else!

<?php
class test1{}
class
test2{}
class
test3{}

function
cache( $class )
{
    static
$loaders = array();
   
   
$loaders[ $class ] = new $class();

   
var_dump( $loaders );
}
print
'<pre>';
cache( 'test1' );
cache( 'test2' );
cache( 'test3' );

?>
up
-2
iphstich at gmail dot com
4 years ago
It seems that static variables defined within a class method or static function are stored separately for the class and each extended class of it.

It's sort of like, every time you extend a class, functions with static variables are re-writen, and the static variable re-created. Even if the function is defined as final!

<?php

class A {
    function
x () { static $x = 0; return ++$x; }
    static function
y () { static $y = 0; return ++$y; }
    final static function
z () { static $z = 0; return ++$z; }
}

class
B extends A { }
class
C extends B { }

// As methods, A and B have different values for x
$a = new A();
echo
$a->x(); // 1
$b = new B();
echo
$b->x(); // 1
echo $b->x(); // 2

// And different instances of C will have the same values for x
$c1 = new C();
$c2 = new C();
$c3 = new C();
echo
$c1->x(); // 1
echo $c2->x(); // 2
echo $c3->x(); // 3

// The same behavior applies to static functions
echo A::y(); // 1
echo B::y(); // 1
echo B::y(); // 2
echo C::y(); // 1
echo C::y(); // 2
echo C::y(); // 3

// The same behavior still applies to FINAL static functions
echo A::z(); // 1
echo B::z(); // 1
echo B::z(); // 2
echo C::z(); // 1
echo C::z(); // 2
echo C::z(); // 3
?>

Tested with version 7.0.13
up
0
nino dot skopac at gmail dot com
8 years ago
Interesting behavior in PHP 5.6.12 and PHP 7 RC3:

<?php
class Foo {
    public function
Bar() {
        static
$var = 0;
       
        return ++
$var;
    }
}

$Foo_instance = new Foo;

print
$Foo_instance->Bar(); // prints 1
print PHP_EOL;

unset(
$Foo_instance);

$Foo_instance2 = new Foo;

print
$Foo_instance2->Bar(); // prints 2
print PHP_EOL;
?>

How can a 2 be printed, since we unseted the whole instance before?

Consider a similar example:

<?php
class Foo {
    public static
$var = 0;
   
    public static function
Bar() {
        return ++
self::$var;
    }
}

$Foo_instance = new Foo;

print
$Foo_instance->Bar(); // prints 1
print PHP_EOL;

unset(
$Foo_instance);

$Foo_instance2 = new Foo;

print
$Foo_instance2->Bar(); // prints 2
print PHP_EOL;
?>

No idea why is this happening.
up
0
alan
17 years ago
Using the global keyword inside a function to define a variable is essentially the same as passing the variable by reference as a parameter:

<?php
somefunction
(){
   global
$var;
}
?>

is the same as:

<?php
somefunction
(& $a) {

}
?>

The advantage to using the keyword is if you have a long list of variables  needed by the function - you dont have to pass them every time you call the function.
up
0
jameslee at cs dot nmt dot edu
18 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
-1
Ray.Paseur often uses Gmail
10 years ago
Variable "Visibility" in PHP Object Oriented Programming is documented here:
http://php.net/manual/en/language.oop5.visibility.php
up
-1
pedro at worcel dot com
13 years ago
Another way of working with a large ammount of global variables could be the following.

<?php

$var
= "3";
$smarty = new Smarty();

function
headers_set_404() {
extract($globals);

echo
$var . "<br />";
print_r($smarty);

return;

}

?>

Regards,
Droope
up
-1
Hayley Watson
6 years ago
static variables are implicitly initialised to NULL if no explicit initialisation is made.

<?php
function foo()
{
  static
$v;
  echo
gettype($v);
}

foo();
?>

will echo NULL without complaining that $v is undefined.

In short: "static $v;" is equivalent to "static $v = null;".
up
-2
nullhility at gmail dot com
15 years ago
Like functions, if you declare a variable in a class, then set it as global in that class, its value will not be retained outside of that class either.

<?php
class global_reference
{
    public
$val;
   
    public function
__construct () {
        global
$var;
       
$this->val = $var;
    }
   
    public function
dump_it ()
    {
       
debug_zval_dump($this->val);
    }
   
    public function
type_cast ()
    {
       
$this->val = (int) $this->val;
    }
}
$var = "x";
$obj = new global_reference();
$obj->dump_it();
$obj->type_cast();
echo
"after change ";
$obj->dump_it();
echo
"original $var\n";
?>

The work-around is of course changing the assignment in the constructor to a reference assignment as such:

<?php
   
//....
       
$this->val = &var;
   
//....
?>

If the global you're setting is an object then no reference is necessary because of the way PHP deals with objects. If you don't want to reference to the same object however you can use the clone keyword.

<?php
//...
   
global $Obj;
   
$this->obj_copy = clone $Obj;
//...
?>

[EDIT BY danbrown AT php DOT net:  Merged all thoughts and notes by this author into a single note.]
up
-2
Ganlv
7 years ago
<?php
$var
= 1;
function
foo() {
   
$var = &$GLOBALS['var'];
   
var_dump($var);
}
function
bar() {
    global
$var; // they are the same.
   
var_dump($var);
}
foo();
bar();
var_dump($var);
?>

In a function, 'global $var;' is to declare a local variant, and the local $var has the same reference to the global $var.

<?php
$var
= 1;
function
foo() {
    global
$var;
    unset(
$var);               // unset local $a, the global $a is still there.
   
var_dump($var);            // Undefined variable: var
   
var_dump($GLOBALS['var']); // this is ok.
}
foo();
var_dump($var);                // this is ok.
?>

<?php
$var
= 1;
function
bar() {
    global
$var;
    unset(
$GLOBALS['var']);    // unset global $a, the local $a is still here.
   
var_dump($var);            // this is ok.
   
var_dump($GLOBALS['var']); // Undefined index: var
}
foo();
var_dump($var);                // Undefined variable: var
?>

'unset($var);' is like 'var = NULL;'(var is a pointer) in the C language, instead of 'free(var);'
up
-1
ketansheladiya1
4 years ago
As per PHP standards
The new operator returns a reference automatically, so assigning the result of new by reference is not allowed as of PHP 7.0.0, results in an E_DEPRECATED message as of PHP 5.3.0, and an E_STRICT message in earlier versions.
https://www.php.net/manual/en/language.operators.assignment.php

so you can use following code to check

<?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();
?>
up
-2
Semyon Naitur
6 years ago
function f(){
    global $a; // global $a is declared, local reference is created
    $a = 'a';  // global $a is set
    unset($a); // local reference is unset, global $a remains set
    $a = 'b';  // local $a is declared and set
}
f();
echo $a; // prints 'a'

function f(){
    global $a; // global $a is declared, local reference is created
    $a = 'a';  // global $a is set
    unset($a); // local reference $a is unset, global var $a remains set
    global $a; // local reference is created again
    $a .= 'b';
}
f();
echo $a; // prints 'ab'
To Top