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

search for in the

Variables pré-définies> <Définition du type
[edit] Last updated: Mon, 01 Nov 2010

view this page in

Chapitre 12. Les variables

Essentiel

En PHP, les variables sont représentées par un signe dollar "$" suivi du nom de la variable. Le nom est sensible à la casse (i.e. $x != $X).

Les noms de variables suivent les mêmes règles de nommage que les autres entités PHP. Un nom de variable valide doit commencer par une lettre ou un souligné (_), suivi de lettres, chiffres ou soulignés. Exprimé sous la forme d'une expression régulière, cela donne : '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Note : Dans nos propos, une lettre peut être une des lettres minuscules (a à z) ou majuscules (A à Z) et les caractères ASCII de 127 à 255 (0x7f-0xff).

Astuce : Vous pourriez également avoir besoin de jeter un oeil sur Annexe R.

Pour obtenir des informations sur une variable, voyez les fonctions dédiées aux variables.

Exemple 12-1. Validité des noms de variables

<?php
$var
= 'Jean';
$Var = 'Paul';
echo
"$var, $Var";         // affiche "Jean, Paul"

$4site = 'pas encore';     // invalide : commence par un nombre
$_4site = 'pas encore';    // valide : commence par un souligné
$täyte = 'mansikka';    // valide : 'ä' est ASCII (étendu) 228.
?>

En PHP 3, les variables sont toujours assignées par valeur. C'est-à-dire, lorsque vous assignez une expression à une variable, la valeur de l'expression est recopiée dans la variable. Cela signifie, par exemple, qu'après avoir assigné la valeur d'une variable à une autre, modifier l'une des variables n'aura pas d'effet sur l'autre. Pour plus de détails sur ce genre d'assignation, reportez-vous aux expressions.

Depuis PHP 4, PHP permet aussi d'assigner les valeurs aux variables par référence. Cela signifie que la nouvelle variable ne fait que référencer (en d'autres terme, "devient un alias de", ou encore "pointe sur") la variable originale. Les modifications de la nouvelle variable affecteront l'ancienne et vice versa.

Pour assigner par référence, ajoutez simplement un & (ET commercial) au début de la variable qui est assignée (la variable source). Dans l'exemple suivant, Mon nom est Pierre s'affichera deux fois :

Exemple 12-2. Assignation de référence

<?php
$foo
= 'Pierre';              // Assigne la valeur 'Pierre' à $foo
$bar = &$foo;                 // Référence $foo avec $bar.
$bar = "Mon nom est $bar"// Modifie $bar...
echo $foo;                    // $foo est aussi modifiée
echo $bar;
?>

Une chose importante à noter est que seules les variables nommées peuvent être assignées par référence.

Exemple 12-3. Assignation de référence et variables anonymes

<?php
$foo
= 25;
$bar = &$foo;      // assignation valide
$bar = &(24 * 7);  // assignation invalide : référence une expression sans nom
function test() {
   return
25;
}
$bar = &test();    // assignation invalide.
?>

Il n'est pas nécessaire d'initialiser les variables en PHP, cepedant, cela reste une excellente pratique. Les variables non initialisées ont une valeur par défaut selon leurs types - FALSE, zéro, chaîne vide ou un tableau vide.

Exemple 12-4. Valeurs par défaut des variables non initialisées

<?php
echo ($unset_bool ? "true" : "false"); // false
$unset_int += 25; // 0 + 25 => 25
echo $unset_string . "abc"; // "" . "abc" => "abc"
$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
?>

Utiliser la valeur par défaut d'une variable non initialisée est problèmatique lorsque vous incluez un fichier dans un autre qui utilise le même nom de variable. C'est également un risque niveau sécurité lorsque register_globals est activé. Une erreur de niveau E_NOTICE sera émise lorsque vous travaillerez avec des variables non initialisées, cependant, aucune erreur ne sera lancée lorsque vous tenterez d'insérer un élément dans un tableau non initialisé. La structure de langage isset() peut être utilisée pour détecter si une variable a déjà été initialisée.



Variables pré-définies> <Définition du type
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Les variables
james at custom-made-sites dot com 30-Sep-2010 04:55
This script has been running around for a while and has add many additions and changes, however I noticed that if you run it and there is an object assigned to a variable it will fail with 'Object of Class 'XXXX' cannot be converted to string'
so I changed it a little to ignore objects within the script and display the variables only:

Btw, it has haelped me an ENOURMOUS amount over the years especially when keeping track of variables that are being sent through request and if session variables are alive

<?php

//this can be removed if you want to find out if you page has actually started a session, - this is sometimes a problem when relying on a session being started by an included/required file
if(!isset($_SESSION))
{
session_start();
}

//now begin the table
echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>';
foreach(
get_defined_vars() as $key => $value)
{
//if the returned value is NOT an object...
   
if (is_array ($value) && !is_object($key) && !is_object($value))
    {
        echo
'<tr><td>$'.$key .'</td><td>';
        if (
sizeof($value)>0 )
        {
        echo
'"<table border=1><tr> <th>key</th> <th>value</th> </tr>';
        foreach (
$value as $skey => $svalue )
        {
 
//and if these values are NOT an object...

   
if ( !is_object($skey) && !is_object($svalue))
    {
            echo
'<tr><td>[' . $skey .']</td><td>"'. $svalue .'"</td></tr>';
    }
        }
        echo
'</table>"';
        }
             else
        {
            echo
'EMPTY';
        }
        echo
'</td></tr>';
    }else

    {
            echo
'<tr><td>[' . $key .']</td><td>"'. $value .'"</td></tr>';
    }
   
   
   
}

echo
'</table>';
?>
justgook at gmail dot com 03-Aug-2010 01:38
I found interstate solution to work with arrays

<?php
$vars
['product']['price']=11;

$aa='product';
$bb='price';

echo
$vars{$aa}{$bb};

//prints 11
?>
dimitrov dot adrian at gmail dot com 29-Jul-2010 06:52
This is mine type casting lib, that is very useful for me.

<?php

function CAST_TO_INT($var, $min = FALSE, $max = FALSE)
{
   
$var = is_int($var) ? $var : (int)(is_scalar($var) ? $var : 0);
    if (
$min !== FALSE && $var < $min)
        return
$min;
    elseif(
$max !== FALSE && $var > $max)
        return
$max;
    return
$var;
       
}

function
CAST_TO_FLOAT($var, $min = FALSE, $max = FALSE)
{
   
$var = is_float($var) ? $var : (float)(is_scalar($var) ? $var : 0);
    if (
$min !== FALSE && $var < $min)
        return
$min;
    elseif(
$max !== FALSE && $var > $max)
        return
$max;
    return
$var;
}

function
CAST_TO_BOOL($var)
{
    return (bool)(
is_bool($var) ? $var : is_scalar($var) ? $var : FALSE);
}

function
CAST_TO_STRING($var, $length = FALSE)
{
    if (
$length !== FALSE && is_int($length) && $length > 0)
        return
substr(trim(is_string($var)
                    ?
$var
                   
: (is_scalar($var) ? $var : '')), 0, $length);

    return
trim(
               
is_string($var)
                ?
$var
               
: (is_scalar($var) ? $var : ''));
}

function
CAST_TO_ARRAY($var)
{
    return
is_array($var)
            ?
$var
           
: is_scalar($var) && $var
               
? array($var)
                :
is_object($var) ? (array)$var : array();
}

function
CAST_TO_OBJECT($var)
{
    return
is_object($var)
            ?
$var
           
: is_scalar($var) && $var
               
? (object)$var
               
: is_array($var) ? (object)$var : (object)NULL;
}

?>
Anonymous 20-Jul-2008 06:25
[EDIT by danbrown AT php DOT net: The function provided by this author will give you all defined variables at runtime.  It was originally written by (john DOT t DOT gold AT gmail DOT com), but contained some errors that were corrected in subsequent posts by (ned AT wgtech DOT com) and (taliesin AT gmail DOT com).]

<?php

echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>';
foreach(
get_defined_vars() as $key => $value)
{
    if (
is_array ($value) )
    {
        echo
'<tr><td>$'.$key .'</td><td>';
        if (
sizeof($value)>0 )
        {
        echo
'"<table border=1><tr> <th>key</th> <th>value</th> </tr>';
        foreach (
$value as $skey => $svalue)
        {
            echo
'<tr><td>[' . $skey .']</td><td>"'. $svalue .'"</td></tr>';
        }
        echo
'</table>"';
        }
             else
        {
            echo
'EMPTY';
        }
        echo
'</td></tr>';
    }
    else
    {
            echo
'<tr><td>$' . $key .'</td><td>"'. $value .'"</td></tr>';
    }
}
echo
'</table>';
?>
alexandre at nospam dot gaigalas dot net 06-Jul-2007 09:13
Here's a simple solution for retrieving the variable name, based on the lucas (http://www.php.net/manual/en/language.variables.php#49997) solution, but shorter, just two lines =)

<?php
function var_name(&$var, $scope=0)
{
   
$old = $var;
    if ((
$key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key
}
?>
jsb17 at cornell dot edu 20-Feb-2007 08:48
As an addendum to David's 10-Nov-2005 posting, remember that curly braces literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable variable creation into one line, like this:

<?php
 
${"title_default_" . $title} = "selected";
?>

and then, for example:

<?php
  $title_select
= <<<END
    <select name="title">
      <option>Select</option>
      <option $title_default_Mr  value="Mr">Mr</option>
      <option $title_default_Ms  value="Ms">Ms</option>
      <option $title_default_Mrs value="Mrs">Mrs</option>
      <option $title_default_Dr  value="Dr">Dr</option>
    </select>
END;
?>
code at slater dot fr 25-Jan-2007 02:10
Here's a pair of functions to encode/decode any string to be a valid php and javascript variable name.

<?php

function label_encode($txt) {
 
 
// add Z to the begining to avoid that the resulting
  // label is a javascript keyword or it starts with a
  // number
 
$txt = 'Z'.$txt;
 
 
// encode as urlencoded data
 
$txt = rawurlencode($txt);
 
 
// replace illegal characters
 
$illegal = array('%', '-', '.');
 
$ok = array('é', 'è', 'à');
 
$txt = str_replace($illegal,$ok, $txt);
 
  return
$txt;
}

function
label_decode($txt) {
 
 
// replace illegal characters
 
$illegal = array('%', '-', '.');
 
$ok = array('é', 'è', 'à');
 
$txt = str_replace($ok, $illegal, $txt);
 
 
// unencode
 
$txt = rawurldecode($txt);
 
 
// remove the leading Z and return
 
return substr($txt,1);
}

?>
molnaromatic at gmail dot com 20-May-2006 05:44
Simple sample and variables and html "templates":
The PHP code:
variables.php:
<?php
$SYSN
["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian
$SYSN["FEAR"] = "Bell in my heart";
?>

index.php:
<?php
include("variables.php");
include(
"template.html");
?>

The template:
template.html

<html>
<head><title><?=$SYSN["title"]?></title></head>
<body>
<H1><?=$SYSN["HEADLINE"]?></H1>
<p><?=$SYSN["FEAR"]?></p>
</body>
</html>
This is simple, quick and very flexibile
Mike at ImmortalSoFar dot com 25-Nov-2005 02:03
References and "return" can be flakey:

<?php
//  This only returns a copy, despite the dereferencing in the function definition
function &GetLogin ()
{
    return
$_SESSION['Login'];
}

//  This gives a syntax error
function &GetLogin ()
{
    return &
$_SESSION['Login'];
}

//  This works
function &GetLogin ()
{
   
$ret = &$_SESSION['Login'];
    return
$ret;
}
?>
david at removethisbit dot futuresbright dot com 10-Nov-2005 01:25
When using variable variables this is invalid:

<?php
$my_variable_
{$type}_name = true;
?>

to get around this do something like:

<?php
$n
="my_variable_{$type}_name";
${
$n} = true;
?>

(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)
Chris Hester 31-Aug-2005 05:09
Variables can also be assigned together.

<?php
$a
= $b = $c = 1;
echo
$a.$b.$c;
?>

This outputs 111.
Mike Fotes 09-Jul-2005 11:46
In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:

<?php
$condition
= true;

// Outputs " <-- That should say test"
echo "test" . ($condition) ? " <-- That should say test" : "";
?>

You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:

<?php
$condition
= true;

// Outputs "test <-- That should say test"
echo "test" . (($condition) ? " <-- That should say test " : "");
?>
josh at PraxisStudios dot com 17-May-2005 01:06
As with echo, you can define a variable like this:

<?php

$text
= <<<END

<table>
    <tr>
        <td>
             $outputdata
        </td>
     </tr>
</table>

END;

?>

The closing END; must be on a line by itself (no whitespace).

[EDIT by danbrown AT php DOT net: This note illustrates HEREDOC syntax.  For more information on this and similar features, please read the "Strings" section of the manual here: http://www.php.net/manual/en/language.types.string.php ]
mike at go dot online dot pt 07-Apr-2005 09:18
In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:

<?php
//considering 2 arrays
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");

//and 2 variables that hold integers
$num = 1;
$cell = 2;

echo ${
foo.$num}[$cell]; // outputs "c"

$num = 2;
$cell = 0;

echo ${
foo.$num}[$cell]; // outputs "d"
?>
lucas dot karisny at linuxmail dot org 14-Feb-2005 04:42
Here's a function to get the name of a given variable.  Explanation and examples below.

<?php
 
function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
  {
    if(
$scope) $vals = $scope;
    else     
$vals = $GLOBALS;
   
$old = $var;
   
$var = $new = $prefix.rand().$suffix;
   
$vname = FALSE;
    foreach(
$vals as $key => $val) {
      if(
$val === $new) $vname = $key;
    }
   
$var = $old;
    return
$vname;
  }
?>

Explanation:

The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.

Examples:

1.  Use of a variable contained in the global scope (default):
<?php
  $my_global_variable
= "My global string.";
  echo
vname($my_global_variable); // Outputs:  my_global_variable
?>

2.  Use of a local variable:
<?php
 
function my_local_func()
  {
   
$my_local_variable = "My local string.";
    return
vname($my_local_variable, get_defined_vars());
  }
  echo
my_local_func(); // Outputs: my_local_variable
?>

3.  Use of an object property:
<?php
 
class myclass
 
{
    public function
__constructor()
    {
     
$this->my_object_property = "My object property  string.";
    }
  }
 
$obj = new myclass;
  echo
vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>
ringo78 at xs4all dot nl 14-Jan-2005 12:27
<?php
// I am beginning to like curly braces.
// I hope this helps for you work with them
$filename0="k";
$filename1="kl";
$filename2="klm";
 
$i=0;
for (
$varname = sprintf("filename%d",$i);   isset  ( ${$varname} ) ;   $varname = sprintf("filename%d", $i)  )  {
    echo
"${$varname} <br>";
   
$varname = sprintf("filename%d",$i);
   
$i++;
}
?>
Carel Solomon 07-Jan-2005 03:02
You can also construct a variable name by concatenating two different variables, such as:

<?php

$arg
= "foo";
$val = "bar";

//${$arg$val} = "in valid";     // Invalid
${$arg . $val} = "working";

echo
$foobar;     // "working";
//echo $arg$val;         // Invalid
//echo ${$arg$val};     // Invalid
echo ${$arg . $val};    // "working"

?>

Carel
raja shahed at christine nothdurfter dot com 25-May-2004 10:58
<?php
error_reporting
(E_ALL);

$name = "Christine_Nothdurfter";
// not Christine Nothdurfter
// you are not allowed to leave a space inside a variable name ;)
$$name = "'s students of Tyrolean language ";

print
" $name{$$name}<br>";
print 
"$name$Christine_Nothdurfter";
// same
?>
webmaster at daersys dot net 20-Jan-2004 08:15
You don't necessarily have to escape the dollar-sign before a variable if you want to output its name.

You can use single quotes instead of double quotes, too.

For instance:

<?php
$var
= "test";

echo
"$var"; // Will output the string "test"

echo "\$var"; // Will output the string "$var"

echo '$var'; // Will do the exact same thing as the previous line
?>

Why?
Well, the reason for this is that the PHP Parser will not attempt to parse strings encapsulated in single quotes (as opposed to strings within double quotes) and therefore outputs exactly what it's being fed with :)

To output the value of a variable within a single-quote-encapsulated string you'll have to use something along the lines of the following code:

<?php
$var
= 'test';
/*
Using single quotes here seeing as I don't need the parser to actually parse the content of this variable but merely treat it as an ordinary string
*/

echo '$var = "' . $var . '"';
/*
Will output:
$var = "test"
*/
?>

HTH
- Daerion
unleaded at nospam dot unleadedonline dot net 14-Jan-2003 06:37
References are great if you want to point to a variable which you don't quite know the value yet ;)

eg:

<?php
$error_msg
= &$messages['login_error']; // Create a reference

$messages['login_error'] = 'test'; // Then later on set the referenced value

echo $error_msg; // echo the 'referenced value'
?>

The output will be:

test

 
show source | credits | sitemap | contact | advertising | mirror sites