I am relatively new to OOP approach to PHP, but just wanted something clarified:
if(isset($_POST['insertProduct']) && !empty($_POST['productName'])){
$newProduct = new product();
$newProduct->productName = $_POST['productName'];
$newProduct->servingSize = $_POST['servingSize'];
$productID = $newProduct->insertProduct();
}
So the above code is executed when a form is posted to the page to enter a new product into the DB.
$selectProduct = new product();
if($selectProduct->getProducts()){
foreach($selectProduct->getProducts() as $product){
echo '<option value="' .
$product['productID'] . '">' .
$product['productName'] . '</option>';
}
}
The above piece is on the same page, and obviously now there are two instances of the product class that exist (assuming the form has been posted to add a new product). Does this show a benefit of the OO approach? As in using two instances to access different methods? Or is it a bad way of doing what I want to do?
I think
getProductsshould be at least a static method, since it doesn’t have nothing to do with the instance of a product.A product class should represent only the single data of a product, therefore generic non-instances methods should be set to static or moved to another class.
I’d suggest you to create a Factory class that will create the
productinstances for you:But you surely need to move that method outside the
productclass.For the rest, everything seems fine.