Variablen & Typen
| $x = 42 | int |
| $x = 3.14 | float |
| $x = "Hi" | string |
| $x = true | bool |
| $x = null | null |
| $x = [1,2,3] | array |
| $x = ['k'=>1] | assoc array |
| gettype($x) | Typ-Name |
| is_int($x) | Typ-Check |
| (int)$x | Cast |
String-Funktionen
| strlen($s) | Länge |
| strtolower | klein |
| strtoupper | groß |
| trim($s) | Whitespace weg |
| explode(',', $s) | → array |
| implode(',', $a) | → string |
| str_replace | a → b |
| str_contains | enthält? |
| sprintf("%d", 1) | format |
| "$name" | Interpolation |
Moderne Klasse (PHP 8)
class User {
public function __construct(
public readonly string $name,
public readonly int $age,
private ?string $email = null,
) {}
public function isAdult(): bool {
return $this->age >= 18;
}
}
$u = new User(name: 'Marek', age: 34);
Array-Funktionen
| count($a) | Anzahl |
| array_map(fn, $a) | transform |
| array_filter | filtern |
| array_reduce | aggregieren |
| array_keys | → Keys |
| array_values | → Values |
| in_array($x, $a) | enthält? |
| array_merge | a + b |
| sort / usort | sortieren |
| array_unique | dedupe |
Control Flow
if ($x > 0) { ... }
elseif ($x < 0) { ... }
else { ... }
match($status) {
'ok', 'good' => 'positiv',
'err' => 'negativ',
default => '?',
};
foreach ($items as $k => $v) { ... }
for ($i=0; $i<10; $i++) { ... }
while ($cond) { ... }
Enums & Match
enum Status: string {
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string {
return match($this) {
self::Draft => 'Entwurf',
self::Published => 'Veröffentlicht',
self::Archived => 'Archiv',
};
}
}
Fehler & Try/Catch
try {
$result = risky();
} catch (\ValueError $e) {
log($e->getMessage());
} catch (\Exception $e) {
throw new \AppError(...);
} finally {
cleanup();
}
Ökosystem
ComposerPaket-Manager
LaravelFull-Stack
SymfonyEnterprise
PHPUnitTests
PHPStanStatic-Analyse
ShopwareE-Commerce
WordPressCMS
DoctrineORM & DBAL
Idiome vs. Anti-Patterns
Idiomatisch
- strict_types=1
- Type-Hints überall
- readonly Properties
- Composer Autoload
- PSR-12 Coding-Style
- match statt switch
Vermeiden
- mysql_* Funktionen
- extract() von User
- eval() jeglicher Art
- Globals ($GLOBALS)
- @-Suppression
- include statt require_once