PHP in 10 Minuten lernen
PHP ist eine weit verbreitete serverseitige Skriptsprache, die für die Webentwicklung entwickelt wurde. Ursprünglich für “Personal Home Pages” erstellt, steht PHP heute für “PHP: Hypertext Preprocessor”. Dieses Tutorial behandelt PHP 8.3+ Features und hilft dir, moderne PHP-Entwicklung schnell zu erlernen.
1. Dein erstes PHP-Programm schreiben
Beginnen wir mit einem einfachen Programm. Erstelle eine Datei namens hello.php
und gib den folgenden Code ein:
<?php
echo "Hello, World!";
?>
Speichere die Datei und führe sie mit einem Webserver oder PHP CLI aus:
php hello.php
Die Ausgabe wird sein:
Hello, World!
Dieses einfache Programm demonstriert PHPs grundlegende Ausgabefunktionalität. Die echo
-Anweisung wird verwendet, um Text anzuzeigen. PHP-Code ist in <?php
und ?>
Tags eingeschlossen.
2. Grundlegende Syntax
PHP-Syntax ist unkompliziert und ähnlich zu C und Perl. PHP-Code wird auf dem Server ausgeführt, und die Ergebnisse werden als reines HTML an den Browser gesendet.
<?php
// This is a single-line comment
echo "Hello, World!";
/*
This is a multi-line comment
spanning multiple lines
*/
?>
Grundlegende Syntaxregeln in PHP:
- PHP-Tags: PHP-Code muss in
<?php ... ?>
Tags eingeschlossen sein - Kommentare: Einzeilige Kommentare verwenden
//
oder#
, mehrzeilige Kommentare verwenden/* ... */
- Anweisungen: Enden mit Semikolon
;
- Groß-/Kleinschreibung: Variablennamen sind case-sensitive, aber Funktionsnamen nicht
- Variablen: Beginnen mit dem
$
Symbol
<?php
$name = "John"; // Variable (case-sensitive)
$Name = "Jane"; // Different variable
echo $name; // Outputs: John
ECHO $Name; // Outputs: Jane (ECHO works same as echo)
?>
3. Variablen und Datentypen
In PHP sind Variablen Container zum Speichern von Daten. PHP ist eine schwach typisierte Sprache, was bedeutet, dass du Variablentypen nicht explizit deklarieren musst.
Regeln für Variablennamen:
- Muss mit dem
$
Symbol beginnen - Kann Buchstaben, Zahlen und Unterstriche enthalten
- Kann nicht mit einer Zahl beginnen
- Case-sensitive
PHPs Hauptdatentypen:
- String: Textdaten in Anführungszeichen
- Integer: Ganze Zahlen
- Float: Dezimalzahlen
- Boolean:
true
oderfalse
- Array: Sammlung von Werten
- Object: Instanz einer Klasse
- NULL: Repräsentiert keinen Wert
- Resource: Verweis auf externe Ressourcen
<?php
$name = "Alice"; // String
$age = 25; // Integer
$height = 5.8; // Float
$is_student = true; // Boolean
$grades = [90, 85, 92]; // Array
$data = null; // NULL
// Type checking
var_dump($name); // string(5) "Alice"
echo gettype($age); // integer
?>
3.1 String-Operationen
Strings können mit einfachen oder doppelten Anführungszeichen definiert werden, mit unterschiedlichem Verhalten:
<?php
$single = 'Single quote string';
$double = "Double quote string";
$name = "John";
$greeting = "Hello, $name!"; // Variable interpolation
$greeting2 = 'Hello, $name!'; // No interpolation
echo $greeting; // Hello, John!
echo $greeting2; // Hello, $name!
// String concatenation
$full_name = "John" . " " . "Doe";
$full_name .= " Jr."; // Append
// String functions
echo strlen($name); // String length: 4
echo strtoupper($name); // JOHN
echo strtolower($name); // john
echo substr($name, 0, 2); // Jo
?>
3.2 Arrays
PHP unterstützt indizierte Arrays, assoziative Arrays und mehrdimensionale Arrays:
<?php
// Indexed array
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5);
// Associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
// Multidimensional array
$students = [
["name" => "Alice", "grade" => 90],
["name" => "Bob", "grade" => 85],
["name" => "Carol", "grade" => 92]
];
// Accessing arrays
echo $fruits[0]; // apple
echo $person["name"]; // John
echo $students[0]["grade"]; // 90
// Array functions
echo count($fruits); // 3
array_push($fruits, "grape"); // Add element
print_r($fruits); // Display array
?>
4. Operatoren
PHP bietet verschiedene Operatoren für unterschiedliche Operationen:
4.1 Arithmetische Operatoren
<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition: 13
echo $a - $b; // Subtraction: 7
echo $a * $b; // Multiplication: 30
echo $a / $b; // Division: 3.333...
echo $a % $b; // Modulus: 1
echo $a ** $b; // Exponentiation: 1000
?>
4.2 Vergleichsoperatoren
<?php
$x = 5;
$y = "5";
var_dump($x == $y); // true (equal value)
var_dump($x === $y); // false (identical type and value)
var_dump($x != $y); // false
var_dump($x !== $y); // true
var_dump($x > 3); // true
var_dump($x <= 5); // true
?>
4.3 Logische Operatoren
<?php
$a = true;
$b = false;
var_dump($a && $b); // false (AND)
var_dump($a || $b); // true (OR)
var_dump(!$a); // false (NOT)
var_dump($a and $b); // false (AND, lower precedence)
var_dump($a or $b); // true (OR, lower precedence)
?>
5. Kontrollstrukturen
5.1 if-Anweisungen
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} elseif ($age >= 13) {
echo "Teen";
} else {
echo "Child";
}
// Ternary operator
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>
5.2 switch-Anweisungen
<?php
$day = "Monday";
switch ($day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
echo "Weekday";
break;
case "Saturday":
case "Sunday":
echo "Weekend";
break;
default:
echo "Invalid day";
}
?>
5.3 Schleifen
for-Schleife:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Number: $i\n";
}
// foreach for arrays
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// foreach with key-value pairs
$person = ["name" => "John", "age" => 30];
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
while- und do-while-Schleifen:
<?php
$count = 0;
while ($count < 3) {
echo "Count: $count\n";
$count++;
}
$num = 0;
do {
echo "Number: $num\n";
$num++;
} while ($num < 3);
?>
6. Funktionen
Funktionen in PHP sind wiederverwendbare Codeblöcke, die spezifische Aufgaben ausführen:
<?php
// Basic function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
// Function with default parameters
function calculate_area($length, $width = 1) {
return $length * $width;
}
echo calculate_area(5); // 5 (width defaults to 1)
echo calculate_area(5, 3); // 15
// Variable arguments
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
// Anonymous functions (closures)
$multiply = function($a, $b) {
return $a * $b;
};
echo $multiply(4, 5); // 20
?>
6.1 Variablen-Geltungsbereich
<?php
$global_var = "I'm global";
function test_scope() {
global $global_var;
$local_var = "I'm local";
echo $global_var; // Accessible with 'global' keyword
echo $local_var; // Local to this function
}
test_scope();
// Static variables
function counter() {
static $count = 0;
$count++;
echo "Count: $count\n";
}
counter(); // Count: 1
counter(); // Count: 2
counter(); // Count: 3
?>
7. Objektorientierte Programmierung
PHP unterstützt objektorientierte Programmierung mit Klassen und Objekten:
<?php
class Person {
// Properties
private $name;
private $age;
public $city;
// Constructor
public function __construct($name, $age, $city = "Unknown") {
$this->name = $name;
$this->age = $age;
$this->city = $city;
}
// Methods
public function getName() {
return $this->name;
}
public function setAge($age) {
if ($age > 0) {
$this->age = $age;
}
}
public function getAge() {
return $this->age;
}
public function introduce() {
return "Hi, I'm {$this->name}, {$this->age} years old from {$this->city}";
}
}
// Creating objects
$person1 = new Person("John", 25, "New York");
$person2 = new Person("Jane", 30);
echo $person1->introduce();
echo $person2->getName();
?>
7.1 Vererbung
<?php
class Animal {
protected $name;
protected $species;
public function __construct($name, $species) {
$this->name = $name;
$this->species = $species;
}
public function makeSound() {
return "{$this->name} makes a sound";
}
public function getInfo() {
return "{$this->name} is a {$this->species}";
}
}
class Dog extends Animal {
private $breed;
public function __construct($name, $breed) {
parent::__construct($name, "Dog");
$this->breed = $breed;
}
public function makeSound() {
return "{$this->name} barks";
}
public function fetch() {
return "{$this->name} fetches the ball";
}
}
$dog = new Dog("Buddy", "Golden Retriever");
echo $dog->getInfo(); // Buddy is a Dog
echo $dog->makeSound(); // Buddy barks
echo $dog->fetch(); // Buddy fetches the ball
?>
8. Fehlerbehandlung
PHP bietet verschiedene Möglichkeiten zur Behandlung von Fehlern und Ausnahmen:
<?php
// Try-catch for exceptions
try {
$result = 10 / 0;
throw new Exception("Custom error message");
} catch (DivisionByZeroError $e) {
echo "Division by zero error: " . $e->getMessage();
} catch (Exception $e) {
echo "General error: " . $e->getMessage();
} finally {
echo "This always executes";
}
// Custom exception class
class CustomException extends Exception {
public function errorMessage() {
return "Custom error on line {$this->getLine()} in {$this->getFile()}: {$this->getMessage()}";
}
}
try {
throw new CustomException("Something went wrong!");
} catch (CustomException $e) {
echo $e->errorMessage();
}
?>
9. Dateioperationen
PHP bietet verschiedene Funktionen für Dateimanipulation:
<?php
// Reading files
$content = file_get_contents("example.txt");
echo $content;
// Writing files
file_put_contents("output.txt", "Hello, PHP!");
// File operations with error handling
if (file_exists("data.txt")) {
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
} else {
echo "File not found";
}
// Working with file handles
$handle = fopen("log.txt", "a");
if ($handle) {
fwrite($handle, "Log entry: " . date("Y-m-d H:i:s") . "\n");
fclose($handle);
}
?>
10. Arbeiten mit Formularen und HTTP
PHP zeichnet sich in der Handhabung von Webformularen und HTTP-Anfragen aus:
<?php
// HTML form (save as form.html)
/*
<form method="POST" action="process.php">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
*/
// Processing form data (process.php)
if ($_POST) {
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
// Validation
if (empty($username) || empty($email) || empty($password)) {
echo "All fields are required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
} else {
// Process the data
echo "Welcome, " . htmlspecialchars($username);
// Hash password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Save to database, etc.
}
}
// Working with GET parameters
$page = $_GET['page'] ?? 1;
$category = $_GET['category'] ?? 'all';
echo "Page: $page, Category: $category";
?>
11. Datenbankoperationen
PHP arbeitet häufig mit Datenbanken, insbesondere MySQL:
<?php
// Database connection using PDO
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb;charset=utf8",
"username",
"password",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Prepared statements (secure)
$stmt = $pdo->prepare("SELECT * FROM users WHERE age > ? AND city = ?");
$stmt->execute([18, "New York"]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "User: " . $row['name'] . "\n";
}
// Insert data
$stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
$stmt->execute(["John Doe", "[email protected]", 25]);
echo "Last inserted ID: " . $pdo->lastInsertId();
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
12. Moderne PHP-Features (PHP 8.0+)
PHP 8.0+ führte viele moderne Features ein:
<?php
// Named arguments (PHP 8.0+)
function createUser($name, $email, $age = 18, $active = true) {
return compact('name', 'email', 'age', 'active');
}
$user = createUser(
name: "John",
email: "[email protected]",
active: false
);
// Match expression (PHP 8.0+)
$status_code = 200;
$message = match($status_code) {
200, 201 => 'Success',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown Status'
};
// Nullsafe operator (PHP 8.0+)
$user_name = $user?->profile?->name ?? 'Unknown';
// Constructor property promotion (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
public int $age = 18,
private bool $active = true
) {}
public function isActive(): bool {
return $this->active;
}
}
$user = new User("John", "[email protected]", 25);
echo $user->name; // John
// Enums (PHP 8.1+)
enum Status {
case PENDING;
case APPROVED;
case REJECTED;
public function label(): string {
return match($this) {
Status::PENDING => 'Pending',
Status::APPROVED => 'Approved',
Status::REJECTED => 'Rejected',
};
}
}
$status = Status::PENDING;
echo $status->label(); // Pending
?>
13. Best Practices und Tipps
Hier sind einige wesentliche PHP Best Practices:
<?php
// 1. Always use PHP opening tags
// Good: <?php
// Avoid: <? (short tags)
// 2. Use prepared statements for database queries
// Prevents SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
// 3. Validate and sanitize input
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
// 4. Use meaningful variable names
// Good:
$user_age = 25;
$is_active = true;
// Bad:
$a = 25;
$flag = true;
// 5. Handle errors gracefully
function divide($a, $b) {
if ($b == 0) {
throw new InvalidArgumentException("Division by zero");
}
return $a / $b;
}
// 6. Use type declarations (PHP 7+)
function calculateTotal(array $items): float {
return array_sum($items);
}
// 7. Organize code with namespaces
namespace App\Models;
class User {
// class implementation
}
// 8. Use composer for dependency management
// composer.json example:
/*
{
"require": {
"monolog/monolog": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
*/
?>
PHP ist eine mächtige und flexible Sprache, perfekt für Webentwicklung. Dieses Tutorial behandelte die wesentlichen Konzepte, die du brauchst, um PHP-Anwendungen zu erstellen. Übe diese Konzepte, erkunde PHP-Frameworks wie Laravel oder Symfony und lerne weiter!