Home > other >  Refactor if else statement into an OOP class that utilizes polymorphism in PHP
Refactor if else statement into an OOP class that utilizes polymorphism in PHP

Time:02-10

The code goes as follows:

if ($type === "DVD") $description = "Size: $description MB";
else if ($type === "Furniture") $description = "Dimensions: $description";
else if ($type === "Book") $description = "Weight: $description kg";

*P.S I'm relatively new to OOP PHP & don't really know how this can be done

CodePudding user response:

Before jumping on the code immediately, question is: what do you plan to achieve?

Looking at the if-else example you have above, I would think the following: 1) Virtual base class objects which has a method getDescription() which needs to be overwritten by derived classes Child classes DVD, Furniture, Book, etc. which implement getDescription () with the specifics to these classes

2) The sheer number of child classes would grow too much because you have an unforeseeable number of product types entering the store, thus have one class only which has members from which description is constructed, e.g. in pseudo Class item(type, measure, unit, description) book = new item("book", "Weight", "kg", 2)

  •  Tags:  
  • Related