CakeFest 2024: The Official CakePHP Conference

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 tanı iletisi olarak E_WARNING (PHP 8.0.0 öncesinde E_NOTICE) üretir. display_errors INI yönergesi tanı iletilerini gizlemek üzere atanırsa 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 edilmelidir, C dilinde küresel değişkenler, özellikle yerel bir tanımla geçersiz kılınmadıkları sürece, işlevler tarafından otomatik olarak erişilebilir olacaktır. Bu bazı sorunlara yol açabilir, ö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_superglobal()
{
echo
$_POST['isim'];
}
?>

Bilginize:

Eğer içerildiği dosya bir işlevin içinde içerilmişse global anahtar sözcüğünün işlevlerin dışında kullanımı bir hataya yol açmaz.

Statik değişkenlerin kullanımı

Değişken etki alanı ile ilgili önemli özelliklerden biri statik değişkenlerdir. Bir statik 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 - Statik 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 - Statik 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.

Statik 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 statik değişkenler

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

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

Statik değişkenlere sabit ifadelerin sonucu olan değerler atanabilir, ancak işlev çağrıları gibi dinamik ifadeler bir ayrıştırma hatasına sebep olur.

Örnek 7 - Statik değişkenlerin bildirimi

<?php
function foo(){
static
$int = 0; // doğru
static $int = 1+2; // doğru
static $int = sqrt(121); // yanlış (bir işlevle atandığı için)

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

PHP 8.1.0 ve sonrasında, statik değişken kullanan bir yöntem miras alındığında (geçersiz kılınmamak şartıyla), statik değişkenlerini ebeveyn yöntemle paylaşmaktadır. Yani, yöntemlerdeki statik değişkenler artık birer statik özellik gibi davranmaktadır.

Örnek 8 - Miras alınan yöntemlerde statik değişken kullanımı

<?php
class Foo {
public static function
counter() {
static
$counter = 0;
$counter++;
return
$counter;
}
}
class
Bar extends Foo {}
var_dump(Foo::counter()); // int(1)
var_dump(Foo::counter()); // int(2)
var_dump(Bar::counter()); // int(3), PHP 8.1.0 öncesi int(1)
var_dump(Bar::counter()); // int(4), PHP 8.1.0 öncesi int(2)
?>

Bilginize:

Statik bildirimler derleme sırasında çözümlenir.

global ve static değişkenlere gönderim

static ve global değişken niteleyicileri gönderim olarak gerçeklenmiş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;
$yeni = new stdClass;
$nesne = &$yeni;
}

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

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 statik olarak saklanmazlar:

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

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

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

echo
'Statik nesne: ';
var_dump($obj);
if (!isset(
$obj)) {
// Statik 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ı:

Statik nesne: NULL
Statik nesne: NULL

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

Bu örnek, bir statik 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.

add a note

User Contributed Notes 9 notes

up
208
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
174
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
29
andrew at planetubh dot com
15 years ago
Took me longer than I expected to figure this out, and thought others might find it useful.

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

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

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

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

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

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

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

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

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

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

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

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

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

global $b;
$b = "something";
up
16
Michael Bailey (jinxidoru at byu dot net)
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
5
gried at NOSPAM dot nsys dot by
8 years ago
In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:

<?php

error_reporting
(E_ALL);

$GLOB = 0;

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

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

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

echo "Value of global variable (via superglobal array GLOBALS): $GLOBALS[GLOB] <hr>";
// check global variable using superglobal array => 1 (got value of local variable $test, new address was used)

echo "Value ol local variable \$test: $test <hr>";
// check local variable that was linked with global using superglobal array => 1 (its value was not affected)

global $GLOB; // update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $test
echo "Value of global variable (via updated local representation set by keyword global): $GLOB <hr>";
// check global variable via local representation => 1 (also value of local variable $test, new address was used)
}

test_references();
echo
"Value of global variable outside of function: $GLOB <hr>";
// check global variable outside function => 1 (equal to value of local variable $test from function, global variable also points to new address)
?>
up
3
jameslee at cs dot nmt dot edu
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
3
dexen dot devries at gmail dot com
7 years ago
If you have a static variable in a method of a class, all DIRECT instances of that class share that one static variable.

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

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

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

Tested with PHP 7.0.16.

<?php

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

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

class
Derived extends Base {}

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

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

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

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

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

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

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

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

<?php

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

functionA();

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

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

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

This is A before functionA is called: .

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