PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<Typen-TricksVordefinierte Variablen>
view the version of this page
Last updated: Sat, 19 Apr 2003

Kapitel 8. Variablen

Grundlegendes

Variablen werden in PHP dargestellt durch ein Dollar-Zeichen ($) gefolgt vom Namen der Variablen. Bei Variablen-Namen wird zwischen Gro�- und Kleinschreibung unterschieden (case-sensitive).

Variablen-Namen werden in PHP nach den gleichen Regeln wie andere Bezeichner erstellt. Ein g�ltiger Variablen-Name beginnt mit einem Buchstaben oder einem Unterstrich ("_"), gefolgt von einer beliebigen Anzahl von Buchstaben, Zahlen oder Unterstrichen. Als regul�rer Ausdruck (regular expression) w�rde das wie folgt ausgedr�ckt: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'.

Anmerkung: Unserem Zweck entspricht also ein Buchstabe von a bis z bzw. A bis Z oder einem ASCII-Zeichen von 127 bis 255 (0x7f bis 0xff).

$var = "Du";
$vaR = "und";
$Var = "ich";
$vAr = "wir lernen PHP"
echo "$var $vaR $Var, $vAr"; // gibt "Du und ich, wir lernen PHP" aus

$4site  = 'nicht jetzt';     // ung�ltig, da Anfang eine Zahl
$_4site = 'nicht jetzt';     // g�ltig, da Unterstrich am Anfang
$t�byte = 'irgendwas';       // g�ltig, da '�' dem ASCII-Wert 228 entspricht

Variablen werden in PHP 3 durch ihren Wert bestimmt. Das heisst, wenn Sie einer Variablen einen Ausdruck zuweisen, wird der gesamte Inhalt des Originalausdrucks in die Zielvariable kopiert. Die Folge ist, dass eine Variable, die ihren Inhalt von einer anderen Variablen erhalten hat, ihren Inhalt beh�lt, auch wenn Sie danach den Inhalt der anderen (Quell- / Ursprungs-)Variablen �ndern. Die Inhalte der Ziel- und Quellvariablen sind also insoweit unabh�ngig voneinander. F�r weitere Informationen lesen Sie bitte Expressions / Ausdr�cke.

PHP 4 bietet eine andere M�glichkeit der Wertzuweisung bei Variablen: Zuweisung durch Referenzierung. Das bedeutet, dass der Wert der neuen Variablen eine Referenz zur Ursprungs-Variablen darstellt (mit anderen Worten: Der Wert ist ein Alias bzw. Zeiger auf den Inhalt der Ursprungsvariablen). Beide Variablen zeigen also auf die selbe(n) Speicherstelle(n). �nderungen der neuen Variablen �ndern auch deren Ursprungs- Variable und umgekehrt. Der Wert / Inhalt wird also nicht kopiert. Die �bertragung geschieht dadurch auch schneller als in PHP 3. Dies wird sich aber nur bei umfangreichen Schleifen oder bei der �bertragung von grossen Arrays oder Objekten bemerkbar machen.

F�r die Zuweisung per Referenz m�ssen Sie lediglich ein & der (Ausgangs-, Quell-) Variablen voranstellen, die sie einer anderen Variablen zuweisen wollen. Der folgende Skript- Ausschnitt wird zweimal 'Mein Name ist Bob' ausgeben:

<?php
$foo = 'Bob';             // 'Bob' der Variablen $foo zuweisen.
$bar = &$foo;             // Zeiger auf $foo in $bar erzeugen.
$bar = "My name is $bar"; // $bar ver�ndern...
echo $foo;                // $foo wurde dadurch ebenfalls ver�ndert.
echo $bar;
?>

Zu beachten ist, dass nur Variablenbezeichner referenziert werden k�nnen.

<?php
$foo = 25;
$bar = &$foo;     // G�ltige Zuweisung.
$bar = &(24 * 7); // Ung�ltig, da kein Variablenbezeichner
                  // zugewiesen wird.
function test() {
    return 25;
}

$bar = &();   // Ung�ltig.
?>



User Contributed Notes
Variablen
add a note
risa4 at law dot leidenuniv dot nl
23-Mar-2001 11:31

If, for some reason you need to declare
a dynamic variable global, say $usertype1, $usertype2 etc...
do it like this:
              $i=1;
               $ready=#number of
                      generated
                       variables#
while ($i < $ready) {

$var="usertype$i";
global $$var;

               ###do the action with
                the var, for
                  example:##
              echo $$var;
$i++;
}

dwood at templar dot com
24-Apr-2001 06:31

I had trouble digging this out, and searches for various terms (memory model, garbage collection, &c) were not productive.


PHP4 uses reference counting for garbage collection. Details about this system can be found here:



webmaster at webpagebydesign dot com
08-Dec-2001 02:12

a great way to pass variables from page to page...
select: How PHP/FI handles GET and POST method data
ie:
  /cgi-bin/php.cgi/[email protected]&var=value
The relevant components of the PHP symbol table will be:

   $argc     = 4
   $argv[0]    = abc
   $argv[1]    = def
  $argv[2]    = [email protected]&var=value
  $EMAIL_ADDR = [email protected]
   $var        = value

engard at all dot NOSPAM dot hu
01-Mar-2002 03:06

Actually, you can use other chars (including spaces) in the variable name, if you are using variable variables. E.g., the following works for me (in PHP 4.1.1):

$x="blah blah-blah";
$$x="value";
echo "var==" . $$x;
echo "var==" . ${"blah blah-blah"};

Its output is:
var==value
var==value

You can use it also in object variables (properties).

cd579 at hotmail dot com
06-Apr-2002 09:16

Another way to assign a variable a large amount text without having to worry about quotes getting in the way is like so:

$aVariable = <<<END
"HEY!"
END;

print "$aVariable";

output:  "HEY!"

Where as this is will produce an error:
$aVariable = ""HEY!"";

isaac at chexbox dot com
14-Apr-2002 03:21

<<------------------< Env. Variables >------------------>
If you are looking for an explanation of environment variables, go to


If you wanted to set environment variables, look into the putenv() function.

stlawson AT sbcglobal DOT net
06-Jul-2002 01:47

In 'ghent's comment on the 'above example' I think he confuses the confusion ;)

Here is the example referred to:

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>

�Reference $foo via $bar�/�Alter $bar�� IS correct, but it is a little obscure.  Here�s what it means:

$bar is assigned a reference to $foo, thus $bar �references� or points to $foo which contains the string �Bob�.  Essentially what is happening here is �Bob� is stored in memory at a particular address.  &$foo returns that address [where �Bob� is stored].  That address is assigned to $bar.  So, in the string �My name is $bar�, $bar �uses� the address it contains to find �Bob� (which is �in� $foo) and thus the string becomes �My name is Bob�. When the string is assigned to $bar, because $bar refers to $foo, it gets assigned to the same address location that �Bob� is stored at, thus �Bob� is overwritten by �My name is Bob�.  The trick here is to realize that $bar behaves as if it is $foo, so when something is assigned to $bar (the alias of $foo), it�s as if it was being assigned to $foo!

After the above script is run, the output will look like this:

 My name is BobMy name is Bob

e.g. both $foo and $bar print the same thing.

In �C++� the same code snippit would look like this:

foo = �Bob� ;
bar = &foo ;
bar = �My name is � + *bar ;

Notice that in C/C++ it is necessary to manually dereference the pointer (*bar) � PHP does this automagically.

BTW: You might think that �echo $bar;� would display the address of $foo � not so!  More PHP automagic ;)

r dot yaker at wiredfusion dot net
18-Aug-2002 04:01

If you use global variables within a function, take note that changing the variable keyword from "global", somewhere down the line, to "return", that that variable can either be one or the other. It can't be both "returned" and "global".

So, if within a function you have on line x:
global $var;

and then on line x+1:
return $var;

that $var becomes no longer global, and instead just and only "returned".

ct at filanet dot dk
24-Oct-2002 11:32

It is not correct that '�' is ASCII 228. In fact, ASCII only defines characters in the range 0-127.

But '�' is character 228 in the ISO 8859-1 (also known as Latin-1) character set.

peka yashuu de
21-Nov-2002 08:56

`that $var becomes no longer global, and instead just and only "returned".`

The reason for this would be, that you return the value of the variable, not the variable itself and a value can`t be global, can it?

someone at somewhere dot com
23-Dec-2002 06:50

The comment from stlawson AT sbcglobal DOT net about the C/C++ isn't quite correct:

You confuse the pointer notation of C/C++ with the reference notation only availible in C++...

True, dreferencing has to be manually done if you use the pointer notation, but not if you use the reference notation...

gabriel at bumpt dot net
13-Jan-2003 04:26

I know this is not a C++ newsgroup, but I just wanted to get things right, after the comment of "someone at somewhere dot com".

The C-like piece of code provided by stlawson DOES use a pointer, and NOT a C++ reference. "someone at somewhere dot com" got confused because type declaration was obviously omitted for clarity reasons. A reference in C++ is almost a type qualifier: a variable is of type "reference to objects of class MyClass". Therefore, one cannot assign &myObj to a variable declared as a "reference to objects of class MyClass". &myObj really identifies a pointer to myObj, and dereference (using * or ->) is requiered.

unleaded at nospam dot unleadedonline dot net
15-Jan-2003 01:37

References are great if you want to point to a variable which you don't quite know the value yet ;)

eg:

$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

phValue at example dot com
04-Mar-2003 01:03

php shows up a var-name conflict if you use the same name for scalar values and arrays:

first we want to use a scalar value:
$scalarValue = 5;
scalarValue holds: 5

But than, you want to use the same name for an array, too,
which seems ok at first glimps:
(sometimes, its hard to find new names for the same purpose..)

$scalarValue = array();
array_push($scalarValue,3);

scalarValue[0] holds: 3

now, all seems ok, since the array assignment went well..
but, where is the scalarValue gone, if we ask for it?
if you echo for it, you ask for the array:
scalarValue holds: $Array
The scalar value has no longer a reference, since it shares the
same name with an array..
such a bug can give you some hard time to dig for!

Tom Andrews at cfl dot rr dot com
03-Apr-2003 08:02

charecter 228 (�) is not in the ascii 0-127 but is in extended ascii, which is 128-255
pekka at SPAMphotography-on-theSPAM dot net
29-Apr-2003 07:55

For us newbies:
During developement time you often want to display only some variables on page for debugging.  With this function you can you can save some typing time.

function printvars ($name,$hidden) {
if ($hidden == "1") print "<!-- ";
foreach ($name as $k) {
global  ${$k};
print "
<b>$$k:</b> "  . ${$k};
}
if ($hidden == "1") print " -->";
return;
}

Use it by first creating an array of variable names (without $'s) you want to display:

$track = array("name","address","car","hobby","favbeer");

and then run the function (use 1 as second parameter if you want to hide the output into html source code):

printvars ($track,0);

daevid at daevid dot com
01-May-2003 12:47

While this may or may not be obvious, to use references with a function, do it like this...

function timeStampNotes($notes)
{
if ($notes != "")
$notes = "\n\n[".date("m/d/Y h:iA")."]"\n".$notes;
}

timeStampNotes(&$contact_notes);

notice that you use the & in the passing, not in the function itself...

If your notes are getting to be large textareas (like with a database), this may be faster than sending it the normal way.

add a note

<Typen-TricksVordefinierte Variablen>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST