setName($name);
$this->setPrice($price);
$this->setCategory($category);
}
// Getter und Setter
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = trim($name);
}
public function getPrice(): float
{
return $this->price;
}
public function setPrice(float $price): void
{
// einfache Validierung, minimum 0
if ($price price = $price;
}
public function getCategory(): string
{
return $this->category;
}
public function setCategory(string $category): void
{
$this->category = trim($category);
}
}
// ---------- FORMULAR-AKTIONEN ----------
if ($_SERVER'REQUEST_METHOD'] === 'POST') {
// Aktion unterscheiden: speichern oder alles löschen
$action = $_POST['action'] ?? 'save';
if ($action === 'clear') {
// Alle löschen
$_SESSION['products'] = [];
} else {
// Speichern
$name = $_POST['name'] ?? '';
$priceRaw = $_POST['price'] ?? '0';
$category = $_POST['category'] ?? '';
// number-Input kommt als String, in float wandeln
$price = (float) str_replace(',', '.', $priceRaw);
// Neues Objekt der Basisklasse erzeugen
$product = new Product($name, $price, $category);
// In Session-Array speichern, Key = uniqid()
$id = uniqid('p_', true);
$_SESSION['products' = $product;
}
// Optional: Redirect, um Formular-Resubmits zu vermeiden
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
?>
Product Webapp
body { font-family: Arial, sans-serif; margin: 20px; }
form { margin-bottom: 20px; }
label { display: block; margin-top: 10px; }
input, select { padding: 5px; width: 250px; max-width: 100%; }
button { margin-top: 15px; padding: 6px 12px; cursor: pointer; }
table { border-collapse: collapse; margin-top: 20px; width: 100%; max-width: 600px; }
th, td { border: 1px solid #ccc; padding: 8px; }
th { background: #eee; }
Produktverwaltung (Session-Demo)
Produktname (type="text")
Preis in € (type="number")
Kategorie
Elektronik
Haushalt
Bücher
Sonstiges
Speichern
Alle löschen
Gespeicherte Produkte (nur ein Feld wird ausgegeben)
Produktname (eine Membervariable)
$product): ?>
getName(), ENT_QUOTES, 'UTF-8'); ?>
Aktuell sind keine Produkte in der Session gespeichert.