PHP 8.4.0 RC3 available for testing

Portée des variables

La portée d'une variable est le contexte dans lequel elle est définie. PHP possède une portée de fonction et une portée globale. Toute variable définie en dehors d'une fonction est limitée à la portée globale. Lorsqu'un fichier est inclus, le code qu'il contient hérite de la portée des variables de la ligne où l'inclusion a lieu.

Exemple #1 Les variables sont locales à la fonction

<?php
$a
= 1;
include
'b.inc'; // La variable $a sera disponible dans b.inc.

?>

Toute variable créée à l'intérieur d'une fonction nommée ou d'une fonction anonyme est limitée à la portée du corps de la fonction. Cependant, les fonctions fléchées lient les variables de la portée parente pour les rendre disponibles dans le corps. Si un fichier est inclus à l'intérieur d'une fonction dans le fichier appelant, les variables contenues dans le fichier appelé seront disponibles comme si elles avaient été définies à l'intérieur de la fonction appelante.

Exemple #2 Exemple de portée de variable locale

<?php
$a
= 1; // portée globale

function test()
{
echo
$a; // La variable $a est indéfinie car elle fait référence à une version locale de $a
}

test();
?>

L'exemple ci-dessus générera un E_WARNING de variable indéfinie (ou un E_NOTICE avant PHP 8.0.0). La raison pour cela est que l'instruction echo utilise la variable locale $a, et celle-ci n'a pas été assignée préalablement dans la fonction. Notez que ce concept diffère un petit peu du langage C dans lequel une variable globale est automatiquement accessible dans les fonctions, à moins d'être redéfinie localement dans la fonction. Cela peut poser des problèmes si vous redéfinissez des variables globales localement. En PHP, une variable globale doit être déclarée à l'intérieur de chaque fonction afin de pouvoir être utilisée dans cette fonction.

Le mot clé global

Le mot-clé global est utilisé pour lier une variable de la portée globale dans une portée locale. Le mot-clé peut être utilisé avec une liste de variables ou une seule variable. Une variable locale sera créée faisant référence à la variable globale du même nom. Si la variable globale n'existe pas, la variable sera créée dans la portée globale et assignée à null.

Exemple #3 Exemple avec global

<?php
$a
= 1;
$b = 2;
function
somme() {
global
$a, $b;
$b = $a + $b;
}
somme();
echo
$b;

L'exemple ci-dessus va afficher :

3

En déclarant globales les variables $a et $b locales de la fonction somme(), toutes les références à ces variables concerneront les variables globales. Il n'y a aucune limite au nombre de variables globales qui peuvent être manipulées par une fonction.

Une deuxième méthode pour accéder aux variables globales est d'utiliser le tableau associatif pré-défini $GLOBALS. Le précédent exemple peut être réécrit de la manière suivante :

Exemple #4 Les variables globales et $GLOBALS

<?php
$a
= 1;
$b = 2;
function
somme() {
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
somme();
echo
$b;
?>

Le tableau $GLOBALS est un tableau associatif avec le nom des variables globales comme clé et les valeurs des éléments du tableau comme valeur des variables. Notez que $GLOBALS existe dans tous les contextes, car $GLOBALS est un superglobal. Voici un exemple des super globaux :

Exemple #5 Exemple montrant les superglobales et la portée

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

Note: L'utilisation du mot clé global à l'extérieur d'une fonction n'est pas une erreur. Il peut être utilisé si le fichier est inclus depuis l'intérieur d'une fonction.

Utilisation des variables static

Une autre caractéristique importante de la portée des variables est la notion de variable static. Une variable statique a une portée locale uniquement, mais elle ne perd pas sa valeur lorsque le script appelle la fonction. Prenons l'exemple suivant :

Exemple #6 Les variables statiques

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

Cette fonction est un peu inutile car à chaque fois qu'elle est appelée, elle initialise $a à 0 et affiche "0". L'incrémentation de la variable ($a++) ne sert pas à grand chose, car dès que la fonction est terminée, la variable $a disparaît. Pour faire une fonction de comptage utile, c'est-à-dire qui ne perdra pas la trace du compteur, la variable $a est déclarée comme une variable statique :

Exemple #7 Les variables statiques (2)

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

Maintenant, la variable $a est initialisée uniquement lors du premier appel à la fonction et, à chaque fois que la fonction test() est appelée, elle affichera une valeur de $a incrémentée de 1.

Les variables statiques sont essentielles lorsque vous faites des appels récursifs à une fonction. La fonction suivante compte récursivement jusqu'à 10, en utilisant la variable $count pour savoir quand il faut s'arrêter :

Exemple #8 Les variables statiques et la récursivité

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

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

Avant PHP 8.3.0, une variable statique ne pouvait être initialisée qu'en utilisant une expression constante. Depuis PHP 8.3.0, les expressions dynamiques (par exemple, les appels de fonction) sont également autorisées :

Exemple #9 Déclaration de variables statiques

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

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

À partir de PHP 8.1.0, lorsqu'une méthode utilisant des variables statiques est héritée (mais pas surchargée), la méthode héritée partage désormais les variables statiques avec la méthode parente. Cela signifie que les variables statiques dans les méthodes se comportent dorénavant de la même manière que les propriétés statiques.

Exemple #10 Utilisation de variables statiques dans les méthodes héritées

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

Les références avec les variables global et static

PHP implémente les modificateurs de variables static et global, en terme de référence. Par exemple, une vraie variable globale est importée dans un contexte de fonction avec global. Cette commande crée en fait une référence sur la variable globale. Cela peut vous mener à des comportements inattendus, par exemple :

<?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);
?>

L'exemple ci-dessus va afficher :

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

Un comportement similaire s'applique à la commande static. Les références ne sont pas stockées dynamiquement :

<?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();
?>

L'exemple ci-dessus va afficher :

Static object: NULL
Static object: NULL

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

Ces exemples illustrent les problèmes rencontrés lors de l'assignation de référence à des variables statiques, qui sont oubliées lorsque &get_instance_ref() est appelé une seconde fois.

add a note

User Contributed Notes 5 notes

up
224
dodothedreamer at gmail dot com
13 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
177
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
33
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
10
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
20
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";
To Top