Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In a lot of scenarios, procedural programming is just fine. Using OO for the sake of using it is useless, especially if you're just going to end up with <a href="http://en.wikipedia.org/wiki/Plain_old_data_structure" rel="noreferrer">POD</a> objects (plain-old-data).</p> <p>The power of OO comes mainly from inheritance and polymorphism. If you use classes, but never use either of those two concepts, you probably don't need to be using a class in the first place.</p> <p>One of the nicest places IMO that OO shines in, is allowing you to get rid of switch-on-type code. Consider:</p> <pre><code>function drive($the_car){ switch($the_car){ case 'ferrari': $all_cars-&gt;run_ferrari_code(); break; case 'mazerati': $all_cars-&gt;run_mazerati_code(); break; case 'bentley': $all_cars-&gt;run_bentley_code(); break; } } </code></pre> <p>with its OO alternative:</p> <pre><code>function drive($the_car){ $the_car-&gt;drive(); } </code></pre> <p>Polymorphism will allow the proper type of "driving" to happen, based on runtime information.</p> <hr> <p>Notes on polymorphism:</p> <p>The second example here has some premisses: That is that all car classes will either extend an <a href="http://php.net/manual/en/language.oop5.abstract.php" rel="noreferrer">abstract</a> class or implement an <a href="http://php.net/manual/en/language.oop5.interfaces.php" rel="noreferrer">interface</a>.</p> <p>Both allow you to force extending or implementing classes to define a specific function, such as <code>drive()</code>. This is very powerful as it allows you to <code>drive()</code> all cars without having to know which one you're driving; that is because they're extending an abstract class containing the <code>drive()</code> method or implementing an interface forcing the <code>drive()</code> method to be defined.</p> <p>So as long as you make sure that all your specific cars either extend the abstract class <code>car</code> or implement an interface such as <code>canBeDriven</code> (both of which must <em>declare</em> the <code>drive()</code> method) you can just call the <code>drive()</code> method on an object which you know is a car (but not what type of car) without fear of it not being defined, as PHP will throw fatal errors at you until you define those methods in your specific car classes.</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