TOC

This article is currently in the process of being translated into German (~38% done).

Basic PHP:

Variables

Variablen sind einer der wichtigsten Aspekte jeder Programmiersprache. Sie ermöglichen es Ihnen, einen Wert in einem benannten Container zu speichern, für spätere Verwendung oder Manipulation . Das Speichern und Abrufen von Daten aus dem Speicher ist eine komplizierte Aufgabe, aber zum Glück blendet PHP all dieses Low-Level-Material aus und macht es super einfach, Variablen zu deklarieren und zu verwenden.

In PHP können Variablen an den vor ihnen stehenden $ erkannt werden. Das Dollarzeichen wird verwendet, um PHP darüber zu informieren, dass sich der folgende Text auf eine Variable bezieht. Wenn Sie andere Programmiersprachen verwendet haben, können Sie dem Compiler/Interpreter mitteilen, welchen Typ von Variable Sie deklarieren möchten. PHP ist jedoch eine so genannte lose geschriebene Sprache. Es bedeutet, dass Sie eine Variable nicht als einen bestimmten Typ deklarieren müssen - ihr Typ wird von dem bestimmt, was Sie hineingeben. Wir werden im nächsten Kapitel mehr dazu sagen. Lassen Sie uns zunächst mit einigen Variablen arbeiten.

In many other languages, you have to declare a variable before using it, usually with a specific keyword like "var", "dim" or at least the type you wish to use for the variable. But not so with PHP. Just enter the name of it and assign a value, and you're good to go. Here is an example:

<?php
$myVar = "Hello world!";
?>

Now that's pretty simple! You simply write the name of the variable with a dollar sign in front of it, an equal sign, and then you tell PHP what to put inside of the variable. Now, the variable called myVar holds the value of a text string - "Hello world!". Using the variable is even simpler. In this example, we use it with the echo function (it's actually just a language construct and not a function, but that doesn't matter now), which simply outputs it.

<?php
$myVar = "Hello world!";
echo $myVar;
?>

In this example, we used a text string, but we may as well use e.g. a number, like this:

<?php
$myVar = 42;
echo $myVar;
?>

On the other hand, why not just use a text string with the number 42 in it? That's no problem. Try putting quotes around the number in the above example, and you will see that you get the exact same output. But is it in fact the same? No, of course not. While PHP may not seem to care, internally it does, keeping track of the data types you put into your variables. You can read more about that in the chapters about data types.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!