PHP.nl

Variable scope

Variable scope

The scope of a variable is the context within which it is defined. PHP has a function scope and a global scope. Any variable defined outside a function is limited to the global scope. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs.

Voorbeeld: Example of global variable scope

<?php
$a = 1;
include 'b.inc'; // Variable $a will be available within b.inc
?>
Any variable created inside a named function or an
 function
is limited to the scope of the function body.
However, 
bind variables from the parent scope to make them available inside the body.
If a file include occurs inside a function within
the calling file, the variables contained in the called file will be
available as if they had been defined inside the calling function.

anonymousarrow functions

Voorbeeld: Example of local variable scope

<?php
$a = 1; // global scope

function test()
{ 
    echo $a; // Variable $a is undefined as it refers to a local version of $a
}
?>
The example above will generate an undefined variable 
(or an  prior to PHP 8.0.0).
This is because the echo statement
refers to a local version of the  variable,
and it has not been assigned a value within this scope.
Note that this is a little bit different from the C language in
that global variables in C are automatically available to
functions unless specifically overridden by a local definition.
This can cause some problems in that people may inadvertently
change a global variable. In PHP global variables must be
declared global inside a function if they are going to be used in
that function.

E_WARNING``E_NOTICE``$a

The global keyword

 The  keyword is used to bind a variable
 from a global scope into a local scope. The keyword can be used with
 a list of variables or a single variable. A local variable will be created
 referencing the global variable of the same name. If the global
 variable does not exist, the variable will be created in global scope and
 assigned null.
`global`


 
**Voorbeeld: Using **
<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b;
?>
3
By declaring
 and  global within the
function, all references to either variable will refer to the
global version. There is no limit to the number of global
variables that can be manipulated by a function.

$a``$b

A second way to access variables from the global scope is to use
the special PHP-defined  array. The
previous example can be rewritten as:

$GLOBALS

Voorbeeld: Using instead of global

<?php
$a = 1;
$b = 2;

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

Sum();
echo $b;
?>
The  array is an associative array with
the name of the global variable being the key and the contents of
that variable being the value of the array element.
Notice how  exists in any scope, this 
is because  is a .
Here's an example demonstrating the power of superglobals: 

$GLOBALS``$GLOBALS``$GLOBALSsuperglobal

Voorbeeld: Example demonstrating superglobals and scope

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

Opmerking: > Using keyword outside a function is not an error. It can be used if the file is included from inside a function. global

Using static variables

Another important feature of variable scoping is the
 variable. A static variable exists
only in a local function scope, but it does not lose its value
when program execution leaves this scope. Consider the following
example:

static

Voorbeeld: Example demonstrating need for static variables

<?php
function test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>
This function is quite useless since every time it is called it
sets  to  and prints
. The ++ which increments the
variable serves no purpose since as soon as the function exits the
 variable disappears. To make a useful
counting function which will not lose track of the current count,
the  variable is declared static:

$a``0``0``$a``$a``$a

Voorbeeld: Example use of static variables

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>
Now,  is initialized only in first call of function
and every time the  function is called it will print the
value of  and increment it.

$a``test()``$a

Static variables also provide one way to deal with recursive
functions. The following
simple function recursively counts to 10, using the static
variable  to know when to stop:

$count

Voorbeeld: Static variables with recursive functions

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

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

Prior to PHP 8.3.0, static variables could only be initialized using a constant expression. As of PHP 8.3.0, dynamic expressions (e.g. function calls) are also allowed:

Voorbeeld: Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct 
    static $int = 1+2;        // correct
    static $int = sqrt(121);  // correct as of PHP 8.3.0

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

Static variables inside anonymous functions persist only within that specific function instance. If the anonymous function is recreated on each call, the static variable will be reinitialized.

Voorbeeld: Static variables in anonymous functions

<?php
function exampleFunction($input) {
    $result = (static function () use ($input) {
        static $counter = 0;
        $counter++;
        return "Input: $input, Counter: $counter\n";
    });

    return $result();
}

// Calls to exampleFunction will recreate the anonymous function, so the static
// variable does not retain its value.
echo exampleFunction('A'); // Outputs: Input: A, Counter: 1
echo exampleFunction('B'); // Outputs: Input: B, Counter: 1
?>

As of PHP 8.1.0, when a method using static variables is inherited (but not overridden), the inherited method will now share static variables with the parent method. This means that static variables in methods now behave the same way as static properties.

As of PHP 8.3.0, static variables can be initialized with arbitrary expressions. This means that method calls, for example, can be used to initialize static variables.

Voorbeeld: Usage of static Variables in Inherited Methods

<?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), prior to PHP 8.1.0 int(1)
var_dump(Bar::counter()); // int(4), prior to PHP 8.1.0 int(2)
?>

References with global and static variables

PHP implements the
 and 
 modifier 
for variables in terms of . For example, a true global variable
imported inside a function scope with the 
statement actually creates a reference to the global variable. This can
lead to unexpected behaviour which the following example addresses:

staticglobalreferencesglobal

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

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

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
NULL
object(stdClass)#1 (0) {
}
A similar behaviour applies to the  statement.
References are not stored statically:

static

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

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

function &get_instance_noref() {
    static $obj;

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

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>
Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)#3 (1) {
  ["property"]=>
  int(1)
}
This example demonstrates that when assigning a reference to a static
variable, it is not  when the
 function is called a second time.

remembered&amp;get_instance_ref()