I'm trying to create a list of products in php and when I click send I wanted to store N products in the array, but what happens is that every time I click send it adds a new value and does not keep the old.
form.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Formulario</title>
</head>
<body>
<h1>Produto</h1>
<form action="#" method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="description">Description:</label>
<textarea name="description" id="description" cols="30" rows="10"></textarea>
<label for="price">Price:</label>
<input type="number" name="price" id="price">
<button type="submit">Send</button>
</form>
<?php
include "Product.class.php";
if($_POST){
$product = new Product;
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$product->addProduct($name, $description, $price);
$product->showProducts();
}
?>
</body>
</html>
Product.class.php
<?php
class Product
{
public $products;
public function addProduct($name, $description, $price){
return $this->products[] = [$name, $description, $price];
}
public function showProducts(){
echo "<pre>";
var_dump($this->products);
echo "</pre>";
}
}