Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I implement abstraction in this scenario?
    text
    copied!<p>I have a parent class <code>Product</code> and two child classes: <code>Toothbrush</code> and <code>Chainsaw</code>. They are set-up as shown below. </p> <p>Here's the parent class:</p> <pre><code>class Product { protected $productid; protected $type; public function __construct( $productid ) { $this-&gt;productid = $productid; // Performs a lookup in the database and then populates the $type property } } </code></pre> <p>.. and here are the children:</p> <pre><code>class Toothbrush extends Product { public function getPrice() { return 5; // returning an integer for simplicity; there's a calculation going on here } } class Chainsaw extends Product { public function getPrice() { return 1000; // in USD } } </code></pre> <p>I want to iterate through a list of <code>$productid</code>'s and get the corresponding price of the items regardless of whether they are <code>chainsaw</code>'s or <code>toothbrush</code>es.</p> <h2>The problem (or is it?)</h2> <p>Now I've heard over and over again that <strong>a parent class should NOT rely on the child class</strong> to implement functionality (yes I read <a href="https://stackoverflow.com/questions/12934744/calling-a-child-method-from-the-parent-class-in-php">this question</a>, along with many others).</p> <p>Which is why I'm led to think that the solution I'm currently using (below) isn't optimal:</p> <pre><code>class Product { ... public function getPrice() { switch($this-&gt;type) { case 'toothbrush': $theproduct=new Toothbrush($this-&gt;productid); return $theproduct-&gt;getPrice(); break; case 'chainsaw': $theproduct=new Chainsaw($this-&gt;productid); return $theproduct-&gt;getPrice(); break; } } } </code></pre> <p>I can obviously sense that something is remiss here (I shudder to think of what would happen when I get 30 different product types). I've read about abstraction, interfaces, and inheritance and can't figure out which one would work in this scenario.</p> <p>Thank you!</p> <h2>EDIT</h2> <p>Seeing alot of answers, but none that've nailed it just yet. Here is the main point: <strong>How do I call a child method if have only a productid?</strong> (In the above scenario, the <code>Product</code> class retrieves the type from the database in the constructor and populates the <code>$type</code> property accordingly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload