downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Değişken değişkenler> <Öntanımlı Değişkenler
Last updated: Fri, 27 Nov 2009

view this page in

Değişken etki alanı

Bir değişkenin etki alanı içinde tanımlandığı bağlamdır. Hemen her PHP değişkeninin sadece tek bir etki alanı vardır. Bu tek etki alanı betiğe include() ve require() ile dahil edilen dosyalara da uzanır. Örneğin:

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

Burada $a değişkeni içerilen b.inc betiğinin içinde mevcut olacaktır. Fakat, kullanıcı tanımlı işlevlerin etki alanı işleve özeldir. Yani, bir işlev içinde kullanılan herhangi bir değişkenin etki alanı öntanımlı olarak işlevin yerel etki alanı ile sınırlıdır. Örneğin:

<?php
$a 
1/* küresel etki alanı */

function deneme()
{
    echo 
$a/* işlevin etki alanı */
}

deneme();
?>

Bu betik herhangi bir çıktı üretmeyecektir, çünkü echo ifadesi $a değişkeninin yerel sürümüne atıf yapmakta olup bu etki alanı içinde değişkene bir değer atanmamıştır. Bunun C dilinden bir miktar farklı olduğuna dikkat etmiş olabilirsiniz, C dilinde küresel değişkenler, özellikle yerel bir tanımla geçersiz kılınmadıkları sürece, işlevler tarafından özdevinimli olarak erişilebilir olacaktır. Bu bazı sorunlara neden olabilir, öyle ki birileri dikkatsizlikle küresel değişkeni değiştirebilir. PHP'de küresel değişkenler eğer bir işlev içinde kullanılacaksa, o işlev içinde global sözcüğü ile bildirilmeleri gerekir.

global anahtar sözcüğü

İlk olarak, global kullanımına bir örnek verelim:

Örnek 1 - global kullanımı

<?php
$a 
1;
$b 2;

function 
topla()
{
    global 
$a$b;

    
$b $a $b;
}

topla();
echo 
$b;
?>

Yukarıdaki betik 3 çıktısı verecektir. $a ve $b işlev içinde küresel tanımlanarak, her iki değişkene yapılan bütün atıflar küresel sürüme yapılmış olacaktır. Bir işlev tarafından işlenebilecek küresel değişken sayısında bir sınır yoktur.

Küresel etki alanındaki değişkenlere erişimin ikinci yolu PHP tarafından tanımlanmış özel $GLOBALS dizisini kullanmaktır. Önceki örnek şu şekilde yazılabilir:

Örnek 2 - global yerine $GLOBALS kullanımı

<?php
$a 
1;
$b 2;

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

topla();
echo 
$b;
?>

$GLOBALS dizisi, anahtarı küresel değişkenin ismi, elemanının değeri değişkenin içeriği olan bir ilişkisel dizidir. $GLOBALS dizisinin her etki alanında mevcut oluşuna dikkat edin, bunun sebebi$GLOBALS dizisinin bir süper küresel olmasıdır. Süper küresellerin gücünü gösteren bir örnek aşağıda verilmiştir:

Örnek 3 - Süper küreselleri ve etki alanlarını gösteren örnek

<?php
function test_global()
{
    
// Çoğu öntanımlı değişken "süper" değildir ve işlev etki
    // alanında geçerli olmak 'global' olmayı gerektirir.
    
global $HTTP_POST_VARS;

    echo 
$HTTP_POST_VARS['isim'];

    
// Süper küreseller her etki alanında geçerlidirler ve
    // 'global' olarak bildirilmeleri gerekmez. Süper küreseller
    // PHP 4.1.0'dan beri mevcutturlar ve HTTP_POST_VARS'ın
    // kullanımı artık önerilmemektedir.
    
echo $_POST['isim'];
}
?>

Duruk değişkenlerin kullanımı

Değişken etki alanı ile ilgili önemli özelliklerden biri duruk değişkenlerdir. Bir duruk bir değişken sadece işlevin etki alanında geçerli olup, programın çalışması bu etki alanını terkettiği zaman değerini kaybetmez. Aşağıdaki örneğı ele alalım:

Örnek 4 - Duruk değişkenlere ihtiyacı gösteren örnek

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

Bu işlev her çağrıldığında $a'yı 0 yapar ve 0 yazdırır, bu nedenle oldukça kullanışsızdır. Değişkeni artıran $a++ bir işe yaramaz çünkü işlev çıktığı gibi $a değişkeni kaybolur. Kaldığı değeri kaybetmeyecek kullanışlı bir sayaç işlevi yapması için $a değişkeni aşağıda static olarak bildirilmiştir.

Örnek 5 - Duruk değişkenlerin kullanım örneği

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

Artık, $a değişkeni sadece dene() işlevinin ilk çağrılışında ilklendirilecek ve işlevin her çağrılışında $a değişkeninin değerini bastıktan sonra değerini bir artıracaktır.

Duruk değişkenler aynı zamanda kendini çağıran işlevlerle çalışmak için de bir yol sunar. Kendini çağıran (recursive) işlev kendi kendini çağırır. Böyle bir işlev dikkatli yazılmazsa sonsuza kadar kendi kendini çağırır. Kendini çağırmayı bir noktada sonlandıracak uygun bir yönteminiz olmalıdır. Aşağıdaki basit işlev, kendini çağırmayı nerede durduracağını bilerek 10'a kadar sayar:

Örnek 6 - Kendini çağıran işlevlerle duruk değişkenler

<?php
function say()
{
    static 
$sayaç 0;

    
$sayaç++;
    echo 
"$sayaç\n";
    if (
$sayaç 10) {
        
say();
    }
    
$sayaç--;
}
say();
?>

Bilginize: Duruk değişkenler yukarıdaki örneklerde yapıldığı gibi tanımlanabilir. Bu değişkenlere ifadelerin sonuçlarını değer olarak atamaya çalışmak çözümleme hatasına neden olacaktır.

Örnek 7 - Duruk değişken bildirimi

<?php
function foo(){
    static 
$int 0;          // doğru
    
static $int 1+2;        // yanlış  (ifade olduğu için)
    
static $int sqrt(121);  // yanlış  (bu da ifade olduğu için)

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


global ve static değişkenlere gönderim

PHP 4'ün işletmeni olan Zend Motoru 1, static ve global değişken niteleyicilerini gönderim olarak gerçeklemiştir. Örneğin, global deyimi ile bir işlevin etki alanında geçerli kılınan bir küresel değişken aslında kendine bir gönderim oluşturur. Bu durum aşağıdaki örnekte de görüldüğü gibi beklenmedik davranışlara yol açabilir:

<?php
function gönderimli_küresel_dene() {
    global 
$nesne;
    
$nesne = &new stdclass;
}

function 
gönderimsiz_küresel_dene() {
    global 
$nesne;
    
$nesne = new stdclass;
}

gönderimli_küresel_dene();
var_dump($nesne);
gönderimsiz_küresel_dene();
var_dump($nesne);
?>

Yukarıdaki örneğin çıktısı:


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

Aynı davranış static deyimine de uyar. Gönderimler duruk olarak saklanmazlar:

<?php
function &gönderimli_örnek() {
    static 
$obj;

    echo 
'Duruk nesne: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Duruk değişkene gönderim atayalım
        
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
gönderimsiz_örnek() {
    static 
$obj;

    echo 
'Duruk nesne: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Duruk değişkene nesne atayalım
        
$obj = new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

$nesne1 gönderimli_örnek();
$bu_da_nesne1 gönderimli_örnek();
echo 
"\n";
$nesne2 gönderimsiz_örnek();
$bu_da_nesne2 gönderimsiz_örnek();
?>

Yukarıdaki örneğin çıktısı:


Duruk nesne: NULL
Duruk nesne: NULL

Duruk nesne: NULL
Duruk nesne: object(stdClass)#3 (1) {
["property"]=>
int(1)
}

Bu örnek, bir duruk değişkene gönderimli atama yapılması halinde, &gönderimli_örnek() işlevi ikinci kez çağrıldığında değişkene atanan değerin saklanmadığını gösterir.



Değişken değişkenler> <Öntanımlı Değişkenler
Last updated: Fri, 27 Nov 2009
 
add a note add a note User Contributed Notes
Değişken etki alanı
Stewart
14-Nov-2009 10:56
A few people have stated already that global doesn't work in a nested function to access variables of the outer function.  However, nobody seems to know why, or even whether there's a way to do it.

After experimenting, I've discovered that it can't be done for this reason: nested functions in PHP aren't really nested functions at all.

Rather, all functions are in global scope.  A function defined within a function is really just a statement that, on execution, adds the function to the global scope.

To see what I mean, try this at home:

<?php
function qwert() {
   
yuiop();
    function
yuiop() {
        echo
'yuiop';
    }
   
yuiop();
}

yuiop();
qwert();
yuiop();
?>

Now delete the one call to yuiop that triggers an error and try again.  Repeat until it runs without error.
moraesdno at gmail dot com
26-Oct-2009 01:17
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>";
?>
pike
27-Aug-2009 04:58
While writing php code that was served as a "view" from within a cms (in my case ezpublish), the "global" keyword seemed to have stopped working in php5. example #1 on this page simply returned "2", not "3".

However, the error was somewhere else. Since my php code was included within other code by the CMS,  the first assignments (a=1,b=2) were apparently not really in the global scope, and hence could not be referenced by the keyword "global" in php5. This worked in php4.

In my particular case, prepending
<code>
global $a,$b;
</code>
to the code (which is invalid php in a root context afaik) fixed it.

$2c,
*-pike
Stephen Dewey
12-Aug-2009 03:06
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');

?>
akam at akameng dot com
12-Jul-2009 02:39
Many Times Globality of variables will be the small issue, after long time I decided to use super globals.

Super globals exists any where:
$_SERVER, $_GET, $_POST .....

Now for example:

<?php
$foo
[] = range(0, 3);
$_POST['foo'] = $foo;
a(); //no parameters needed.
b();
$foo = $_POST['foo'];

Print_r($foo);
/* out

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 1
            [2] => 2
            [3] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
            [3] => 7
        )

    [2] => Array
        (
            [0] => 8
            [1] => 9
            [2] => 10
        )

)

*/
function a(){
   
$_POST['foo'][] = range(4, 7);
}

function
b(){
$_POST['foo'][] = range(8, 10);
}
?>
Note: the key must not be passed by the page via _POST method by the form, else the value will be over written
emartin at sigb dot net
03-Jul-2009 02:32
If you are used to include files which declare global variables, and if you now need to include these files in a function, you will see that those globals are declared in the function's scope and so they will be lost at the end of the function.

You may use something like this to solve this problem:

main_file.php :
<?php

//Some innocent variables which exist before the problem
$a = 42;
$b = 33;
$c = 56;

function
some_function() {
   
//Some variables that we don't want out of the function
   
$saucisse = "saucisse";
   
$jambon = "jambon";
   
   
//Let's include another file
   
$evalt = "require_once 'anothertest_include.php';";
   
$before_eval_vars = get_defined_vars();
    eval(
$evalt);

   
//Let's extract the variables that were defined AFTER the call to 'eval'
   
$function_variable_names = array("function_variable_names" => 0, "before_eval_vars" => 0, "created" => 0);
   
//We can generate a list of the newly created variables by substracting the list of the variables of the function and the list of the variables which existed before the call to the list of current variables at this point
   
$created = array_diff_key(get_defined_vars(), $GLOBALS, $function_variable_names, $before_eval_vars);
   
//Now we globalize them
   
foreach ($created as $created_name => $on_sen_fiche)
        global $
$created_name;
   
//And we affect them
   
extract($created);
   
}

some_function();
print_r(get_defined_vars());

?>

included_file.php :
<?php

//Some variables that we want in the global scope of main_file.php
$included_var_one = 123;
$included_var_two = 465;
$included_var_three = 789;

?>
Leigh Harrison
26-Mar-2009 06:31
External variables in a function

I needed to access dynamically-created variables from an included file within a helper function. Because the list of $path_* variables I needed to access from the other file is itself dynamic, I didn't want to have to declare all possible variables within the function, and I was concerned at the overhead of declaring =all= members of $GLOBALS[] as global. However the following code worked for me:

<?php
 
function makePath($root, $atom) {
   
$pos = strrpos($atom, '/');
    if (
$pos === false) {
      global ${
'path_'.$atom}; 
     
$path = ${'path_'.$atom};
    }
    else {
      global ${
'path_'.substr($atom, 0, $pos)};
     
$path = ${'path_'.substr($atom, 0, $pos)};
    }
    if (
$path)
      return (
$pos === false)
        ?
$root.$path
       
: $root.$path.substr($atom, $pos + 1);
    else
      return
NULL;
  }
?>

Regards,

::Leigh
http://www.else.co.nz/
andrew at planetubh dot com
03-Feb-2009 08:16
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().
nullhility at gmail dot com
29-Jan-2009 03:17
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.]
ddarjany at yahoo dot com
20-Aug-2008 03:15
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";
}

?>
lgrk
28-May-2008 01:41
Useful function:
<?php
function cycle($a, $b, $i=0) {
    static
$switches = array();
    if (isset(
$switches[$i])) $switches[$i] = !$switches[$i]; else !$switches[$i] = true;
    return (
$switches[$i])?$a:$b;
}
?>

Exeample

<?php
for ($i = 1; $i<3; $i++) {
    echo
$i.cycle('a', 'b').PHP_EOL;
    for (
$j = 1; $j<5; $j++) {
        echo
' '.$j.cycle('a', 'b', 1).PHP_EOL;
        for (
$k = 1; $k<3; $k++) {
            echo
'  '.$k.cycle('c', 'd', 2).PHP_EOL;
        }
    }
}
/**
Output:
1a
 1a
  1c
  2d
 2b
  1c
  2d
 3a
  1c
  2d
 4b
  1c
  2d
2b
 1a
  1c
  2d
 2b
  1c
  2d
 3a
  1c
  2d
 4b
  1c
  2d
*/

?>
Thomas
04-Mar-2008 10:06
It might be worth noting in the article that you shouldn't define magic values at global level and use "global" to access them in a function - like I did in the past few years.

Use define() instead.
Anonymous
01-Mar-2008 07:10
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' );

?>
SID TRIVEDI
27-Oct-2007 09:46
<?php
/*
VARIABLE SCOPE : GLOBAL V/S STATIC

If variable $count is defined global as under, instead of static, it does not work well as desired in repeated function calls.

$count = 1; //if not defined STATIC, in each function call, it starts countig from one to 25.
global $count;

which gives folowing output:
0123456789101112131415161718192021222324
Total 24 numbers are printed.
So far 26 function call(s) made.

26272829303132333435363738394041424344454647484950
Total 50 numbers are printed.
So far 52 function call(s) made.
*/

function print_1to50()
{
//    $count = 1;
//    global $count;
   
static $count=1; // Initial assigment of One to $count, static declarion holds the last(previous) value of variable $count in each next function calls.
       
$limit = $count+24;
        while(
$count<=$limit)
        {
        echo
"$count";
       
$count=$count+1;
        }
       
$num_count= $count-1;
        echo
"<br>\n". "Total $num_count numbers are printed.<br>";

        return;
// return statement without parenthesis()or arguments denotes end of a function rather than returning any values to subsequent function call(s).
} // end of while loop

$count=0;
print_1to50();
$count=$count+1;
print
"So far $count function call(s) made.<br><br>";

print_1to50();
$count=$count+1;
print
"So far $count function call(s) made.<br>";
/*
Which gives following output:
12345678910111213141516171819202122232425
Now I have printed 25 numbers.
I have made 1 function call(s).
26272829303132333435363738394041424344454647484950
Now I have printed 50 numbers.
I have made 2 function call(s).
*/

?>
daniel at nohair dot com
09-Sep-2007 08:01
Ah, nested functions.  Thanks for your notes below, search on  page for "nested functions" folks.   This is how this seems to work.

The child function is seen at global level only after they have been seen once.  But, variables inside functions are only reachable within the functions scope.

<?php
$var1
= "This is \$var1 OUTSIDE parent function <br />";
function
parent_function() {
    echo
"Now inside parent <br />";
   
$var1 = "This is \$var1 INSIDE parent function <br />";
   
$var2 = "This is \$var2 INSIDE parent function <br />";
    function
child_function() {
        echo
"now inside child <br />";
       
//global $var1; //Calls var1 outside parent_function;
       
echo $var1; //doesn't work without global;
        // even if we comment out $var1 outside parent function.
        // global $var1 doesn't reach the one inside parent function.
       
echo $var2; //doesn't work; Can't seem to reach parent variables.
   
}
    echo
"Now calling child<br />";
   
//child_function();    //works
}

// child_function(); //causes fatal error: call to undefined function;
parent_function();  //works;
child_function(); //now works;

?>

[EDIT BY danbrown AT php DOT net: The author is referring to http://php.net/manual/en/language.variables.scope.php#52148 and http://php.net/manual/en/language.variables.scope.php#20407 ]
crack wilding
24-Aug-2007 03:04
Another way of dealing with a large number of globals is to declare a single global array and then put all your global variables into it. Like this:

<?php
$_G
= array(
   
'foo' => 'some text',
   
'bar' => 4,
   
'boo' => 'more text,
    '
far' => 'yet more text'
);
?>

Now you just declare the one global array in each function:

<?php
function blah() {
    global $_G;
    echo $_G['
foo']; // or whatever
}
?>

You can freely add to it without having to go back and add variable declarations to your functions. Kinda like using the $GLOBALS superglobal, except you don'
t have to  type so much.
mod
14-Mar-2007 07:03
Can not access to global variables from destructor, if obj is not unseted at the end:

<?php

 
class A
  
{
     function
__destruct()
      {
        global
$g_Obj;
        echo
"<br>#step 2: ";
       
var_dump($g_Obj);
      }

     function
start()
      {
        global
$g_Obj;
        echo
"<br>#step 1: ";
       
var_dump($g_Obj);
      }
   };

 
$g_Obj = new A();        // start here
 
$g_Obj->start();
 
$g_Obj = NULL;        // !!! comment line and result will changed !!!

?>

Result, if line is not commented:

#step 1: object(A)#1 (0) { }
#step 2: object(A)#1 (0) { }

Result, if line is commented:

#step 1: object(A)#1 (0) { }
#step 2: NULL
Rohan
25-Jan-2007 06:11
<?php
$a
= 20;
function
myfunction($b){
   
$a=30;   //Local Variable
   
global $a,$c; //here global $a overrides the local
   
return $c=($b+$a);
}
print
myfunction(40)+$c;
?>

The output of this function will be 120.
alan
12-Sep-2006 05:53
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.
sami doesn't want spam at no-eff-eks com
21-Jul-2006 04:18
PHP 5.1.4 doesn't seem to care about the static keyword. It doesn't let you use $this in a static method, but you can call class methods through an instance of the class using regular -> notation. You can also call instance methods as class methods through the class itself. The documentiation here is plain wrong.

<?php
class Foo {
  public static function
static_fun()
  {
    return
"This is a class method!\n";
  }
 
  public function
not_static_fun()
  {
    return
"This is an instance method!\n";
  }
}

echo
'<pre>';
echo
"From Foo:\n";
echo
Foo::static_fun();
echo
Foo::not_static_fun();
echo
"\n";

echo
"From \$foo = new Foo():\n";
$foo = new Foo();
echo
$foo->static_fun();
echo
$foo->not_static_fun();
echo
'</pre>';
?>

You'll see the following output:

From Foo:
This is a class method!
This is an instance method!

From $foo = new Foo():
This is a class method!
This is an instance method!
larax at o2 dot pl
22-Mar-2006 11:38
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";
franp at free dot fr
11-Feb-2006 12:25
If you want to access a table row using $GLOBALS, you must do it outside string delimiters or using curl braces :

<?php
$siteParams
["siteName"] = "myweb";

function
foo() {
$table = $GLOBALS["siteParams"]["siteName"]."articles"// OK
echo $table; // output  "mywebarticles"
$table = "{$GLOBALS["siteParams"]["siteName"]}articles"; // OK
echo $table; // output  "mywebarticles"
$table = "$GLOBALS[siteParams][siteName]articles";       // Not OK
echo $table; // output  "Array[siteName]article"

$result = mysql_query("UPDATE $table ...");
}
?>

Or use global :

<?php
function foo() {
global
$siteParams;
$table = "$siteParams[siteName]articles";         // OK
echo $table; // output  "mywebarticles"

$result = mysql_query("UPDATE $table ...");
}
?>
marcin
30-Dec-2005 05:07
Sometimes in PHP 4 you need static variabiles in class. You can do it by referencing static variable in constructor to the class variable:

<?php
class test  {

   var
$var;
   var
$static_var;
    function
test()
    {
        static
$s;
       
$this->static_var =& $s;
    }
 
}

 
$a=new test();

 
$a->static_var=4;
 
$a->var=4;
 
 
$b=new test();
 
 echo
$b->static_var; //this will output 4
 
echo $b->var; //this will output nul
?>
warhog at warhog dot net
13-Dec-2005 08:22
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.
tc underline at gmx TLD ch
14-Sep-2005 10:06
Pay attention while unsetting variables inside functions:

<?php
$a
= "1234";
echo
"<pre>";
echo
"outer: $a\n";
function
testa()
{
    global
$a;
    echo
"   inner testa: $a\n";
    unset (
$a);
    echo
"   inner testa: $a\n";
}
function
testb()
{
    global
$a;
    echo
"   inner testb: $a\n";
   
$a = null;
    echo
"   inner testb: $a\n";
}
testa();
echo
"outer: $a\n";
testb();
echo
"outer: $a\n";
echo
"</pre>";
?>

/***** Result:
outer: 1234
   inner testa: 1234
   inner testa:
outer: 1234
   inner testb: 1234
   inner testb:
outer:
******/

Took me 1 hour to find out why my variable was still there after unsetting it ...

Thomas Candrian
thomas at pixtur dot de
08-Aug-2005 03:02
Be careful with "require", "require_once" and "include" inside functions. Even if the included file seems to define global variables, they might not be defined as such.

consider those two files:

---index.php------------------------------
<?php
function foo() {
 require_once(
"class_person.inc");

 
$person= new Person();
 echo
$person->my_flag; // should be true, but is undefined
}

foo();
?>

---class_person.inc----------------------------
<?php
$seems_global
=true;

class
Person {
  public
$my_flag;

 public function 
__construct() {
   global
$seems_global;
  
$my_flag= $seems_global
 
}
}
?>

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

The reason for this behavior is quiet obvious, once you figured it out. Sadly this might not be always as easy as in this example. A solution  would be to add the line...

<?php global $seems_global; ?>

at the beginning of "class_person.inc". That makes sure you set the global-var.

   best regards
    tom

ps: bug search time approx. 1 hour.
jameslee at cs dot nmt dot edu
16-Jun-2005 09:33
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
kouber at php dot net
28-Apr-2005 12:36
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

}
?>
27-Apr-2005 11:46
Be careful if your static variable is an array and you return
one of it's elements: Other than a scalar variable, elements
of an array are returned as reference (regardless if you
didn't define them to be returned by reference).

<?php
function incr(&$int) {
  return
$int++;
}

function
return_copyof_scalar() {
  static
$v;
  if (!
$v)  
   
$v = 1;
  return(
$v);
}

function
return_copyof_arrayelement() {
  static
$v;
  if (!
$v) {
   
$v = array();
   
$v[0] = 1;
  }
  return(
$v[0]);
}

echo
"scalar: ".
    
incr(return_copyof_scalar()).
    
incr(return_copyof_scalar()).
    
"\n";
echo
"arrayelement: ".
    
incr(return_copyof_arrayelement()).
    
incr(return_copyof_arrayelement()).
    
"\n";
?>

Should print

scalar: 11
arrayelement: 11

but it prints:

scalar: 11
arrayelement: 12

as in the second case the arrays element was returned by
reference. According to a guy from the bug reports the
explanation for this behaviour should be somewhere here in
the documentation (in 'the part with title: "References with
global and static variables"'). Unfortunately I can't find
anything about that here. As the guys from the bug reports
are surely right in every case, maybe there is something
missing in the documentation. Sadly I don't have a good
explanation why this happens, so I decided to document at
least the behaviour.
vdephily at bluemetrix dot com
22-Apr-2005 09:51
Be carefull about nested functions :
<?php
// won't work :
function foo1()
{
 
$who = "world";
  function
bar1()
  {
    global
$who;
    echo
"Hello $who";
  }
}

// will work :
function foo2()
{
 
$GLOBALS['who'] = "world";
  function
bar2()
  {
    global
$who;
    echo
"Hello $who";
  }
}

// also note, of course :
function foo3()
{
 
$GLOBALS['who'] = "world";

 
// won't work
 
echo "Hello $who";

 
// will work
 
global $who;
  echo
"Hello $who";
}
?>
pulstar at ig dot com dot br
09-Sep-2004 01:02
If you need all your global variables available in a function, you can use this:

<?php

function foo(parameters) {
  if(
version_compare(phpversion(),"4.3.0")>=0) {
    foreach(
$GLOBALS as $arraykey=>$arrayvalue) {
      global $
$arraykey;
    }
  }
 
// now all global variables are locally available...
}

?>
info AT SyPlex DOT net
01-Sep-2004 12:35
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
?>
Michael Bailey (jinxidoru at byu dot net)
04-Jun-2004 06:43
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.
Randolpho
02-Apr-2004 08:53
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. :)
jmarbas at hotmail dot com
16-Jan-2004 11:34
Whats good for the goose is not always good for the iterative gander. If you declare and initialize the static variable more than once inside a function ie.

<?php
function Test(){
   static
$count = 0;
   static
$count = 1;
   static
$count = 2;
   echo
$count;
}
?>

the variable will take the value of the last declaration. In this case $count=2.

But! however when you make that function recursive ie.

<?php
 
function Test(){
   static
$count = 0;
   static
$count = 1;
   static
$count = 2;

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

Every call to the function Test() is a differenct SCOPE and therefore the static declarations and initializations are NOT executed again. So what Im trying to say is that its OK to declare and initialize a static variable multiple times if you are in one function... but its NOT OK to declare and initialize a static variable multiple times if you call that same function multiple times. In other words the static variable is set once you LEAVE a function (even if you go back into that very same function).
Jack at soinsincere dot com
14-Nov-2003 06:11
Alright, so you can't set a static variable with a reference.
However, you can set a static variable to an array with an element that is a reference:
<?php

class myReference {
    function
getOrSet($array = null) {
        static
$myValue;
        if (!
$array) {
            return
$myValue[0];     //Return reference in array
       
}
       
$myValue = $array;          //Set static variable with array
       
static $myValue;
    }
}

$static = "Dummy";

$dummy = new myReference;
$dummy->getOrSet(array(&$static));

$static = "Test";
print
$dummy->getOrSet();

?>
flobee at gmx dot net
06-Nov-2003 08:26
i found out that on any (still not found) reason the <?php static $val =NULL; ?> is not working when trying to extract the data form the $var with a while statment
e.g.:
<?php
funktion get_data
() {
static
$myarray = null;
   if(
$myarray == NULL) {
    
//get some info in an array();
    
$myarray = array('one','two');
   }
   while(list(
$key,$val) = each( $myarray ) ) {
  
// do something
  
echo "x: $key , y: $val";
   }
}
?>
when using foreach($myarray AS $key => $val) { .... instad of while then i see the result!
ppo at beeznest dot net
09-Jul-2003 01:59
Even if an included file return a value using return(), it's still sharing the same scope as the caller script!

<?php
$foo
= 'aaa';
$bar = include('include.php');
echo(
$foo.' / '.$bar);
?>

where include.php is
<?php
$foo
= 'bbb';
return
$foo;
?>

The output is: bbb / bbb
Not: aaa / bbb
jg at nerd-boy dot net
08-Feb-2003 12:10
It's possible to use a variable variable when specifying a variable as global in a function. That way your function can decide what global variable to access in run-time.

<?php
function func($varname)
{
   global $
$varname;

   echo $
$varname;
}

$hello = "hello world!";
func("hello");
?>

This will print "hello world!", and is roughly the same as passing by reference, in the case when the variable you want to pass is global. The advantage over references is that they can't have default parameters. With the method above, you can do the following.

<?php
function func($varname = FALSE)
{
   if (
$varname === FALSE)
     echo
"No variable.";
   else
   {
     global $
$varname;

     echo $
$varname;
   }
}

$hello = "hello world!";
func("hello");                   // prints "hello world!"
func();                          // prints "No variable."
?>
wjs@sympaticoDOTca
10-Dec-2002 05:03
Becareful where you define your global variables:

This will work:
<?php
  $MyArray
= array("Dog");

  function
SeeArray(){
    global
$MyArray;
    if (
in_array("Dog",$MyArray)){
      foreach (
$MyArray as $Element){
        echo
"$Element <hr/>";
      }
    }
  }

 
SeeArray();
?>

while this will not:
<?php
  SeeArray
();
 
$MyArray = array("Dog");

  function
SeeArray(){
    global
$MyArray;
    if (
in_array("Dog",$MyArray)){ // an error will generate here
     
foreach ($MyArray as $Element){
        echo
"$Element <hr/>";
      }
    }
  }

?>
heatwave at fw dot hu
15-Oct-2002 12:12
Some people (including me) had a problem with defining a long GLOBAL variable list in functions (very error prone). Here is a possible solution. My program parses php file for functions, and compiles GLOBAL variable lists. Then you can just remove from the list those variables which need not be global.

<?php
   
//parser for GLOBAL variable list
   
$pfile=file("myfile.php4");
   
    for(
$i=0;$i<sizeof($pfile);$i++) {
     if(
eregi("function",$pfile[$i])) {
      list(
$part1,$part2)=sscanf($pfile[$i],"%s %s");
      echo
"\n\n $part1 $part2:\nGLOBAL ";
     
     
$varlist=array();
     
$level=0; $end=$i;
      do {
      
$lpar=explode("{",$pfile[$end]);
      
$level+=sizeof($lpar)-1;
      
$lpar=explode("}",$pfile[$end]);
      
$level-=sizeof($lpar)-1;
      
$end++;
      } while((
$end<sizeof($pfile))&&($level>0));
     
$pstr="";
      for(
$j=$i;$j<=$end;$j++) $pstr.=$pfile[$j];
     
$lpar=explode("$",$pstr);
      for(
$j=1;$j<sizeof($lpar);$j++) {
         
eregi('[a-zA-Z_][a-zA-Z0-9_]*',$lpar[$j],$cvar);
       
$varlist[$cvar[0]]=1;
      }
     
array_walk($varlist,'var_print');
     }
    }
function
var_print ($item, $key) {
     echo
"$key,";
 }
?>
30-Apr-2002 08:14
Seems as though when a cookie is saved and referenced as a variable of the same name as the cookie, that variable is NOT global.  If you make a function ro read the value of the cookie, the cooke variable name must be declared as a global.

example:

<?php
function ReturnCookie()
{
       
$cookieName = "Test_Cookie";
        global $
$cookieName;
        if (isset($
$cookieName))
        {
                echo (
"$cookieName is set");
               
$returnvalue = $$cookieName;
        }
        else
        {
               
$newCookieValue = "Test Value";
               
setcookie("$cookieName","$newCookieValue", (time() + 3153600));
                echo (
"made a cookie:" . $newCookieValue ."<BR>");
               
$returnvalue = $newCookieValue;
        }
        echo (
"the cookie that was set is now $returnvalue <BR>");
        return
$returnvalue;
}
?>
huntsbox at pacbell dot net
03-Apr-2002 04:11
Not sure of the implications of this but...
You can create nested functions within functions but you must make sure they aren't defined twice, e.g.:

<?php
function norm($a, $b) {
    static
$first_time = true;
    if (
$first_time) {
        function
square($x) {
            return
$x * $x;
        }
       
$first_time = false;
    }
    return
sqrt(square($a) + square($b));
}

print
square(5); // error, not defined yet
print norm(5,4);
print
"<br>";
print
norm(3,2);
print
square(5); // OK
?>

If you don't include the if ($first_time) you get an error saying you can't define square() twice.  Note that square is not local to the function it just appears there.  The last line successfully accesses square in the page scope.  This is not terribly useful, but interesting.
jochen_burkhard at web dot de
29-Mar-2002 07:47
Please don't forget:
values of included (or required) file variables are NOT available in the local script if the included file resides on a remote server:

remotefile.php:

<?PHP
$paramVal
=10;
?>

localfile.php:

<?PHP
include "http://example.com/remotefile.php";
echo
"remote-value= $paramVal";
?>

Will not work (!!)
steph_rondinaud at club-internet dot fr
09-Feb-2002 12:41
I'm using PHP 4.1.1

While designing a database access class, I needed a static variable that will be incremented for all instances of the class each time the class connected to the database. The obvious solution was to declare a "connection" class variable with static scope. Unfortunatly, php doesn't allow such a declaration.
So I went back to defining a static variable in the connect method of my class. But it seems that the static scope is not inherited: if class "a" inherit the "db access" class, then the "connection" variable is shared among "a" instances, not among both "a" AND "db access" instances.
Solution is to declare the static variable out of the db access class, and declare "global" said variable in the connect method.
admin at essentialhost dot com
04-Feb-2002 02:30
Quick tip for beginners just to speed things up:
If you have a bunch of global variables to import into a function, it's best to put them into a named array like $variables[stuff].
When it's time to import them you just so the following;

<?php
function here() {
 
$vars = $GLOBALS['variables'];
  print
$vars[stuff];

}
?>

This really helps with big ugly form submissions.
tomek at pluton dot pl
10-Dec-2001 06:53
When defining static variables you may use such declarations:

<?php
static $var = 1; //numbers
static $var = 'strings';
static
$var = array(1,'a',3); //array construct
?>

but these ones would produce errors:

<?php
static $var = some_function('arg');
static
$var = (some_function('arg'));
static
$var = 2+3; //any expression
static $var = new object;
?>
danno at wpi dot edu
24-Jul-2001 07:28
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
carpathia_uk at mail dot com
07-May-2001 09:21
On confusing aspect about global scope...

If you want to access a variable such as a cookie inside a function, but theres a chance it may not even be defined, you need to access it using he GLOBALS array, not by defining it as global.

This wont work correctly....

<?php
function isLoggedin()
{
global
$cookie_username;
if (isset(
$cookie_username)
echo
"blah..";
}
?>

This will..

<?php
function isLoggedin()
{
if (isset(
$GLOBALS["cookie_username"]))
echo
"blah..";
}
?>
shevek at anarres dot org
05-Feb-2000 12:51
If you include a file from within a function using include(), the included file inherits the function scope as its own global scope, it will not be able to see top level globals unless they are explicit in the function.

<?php
$foo
= "bar";
function
baz() {
    global
$foo; # NOTE THIS
   
include("qux");
}
?>

Değişken değişkenler> <Öntanımlı Değişkenler
Last updated: Fri, 27 Nov 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites