Note that there are some explanatory texts on larger screens.

plurals
  1. PODesign patterns - anti pattern call super - avoid or keep
    text
    copied!<p>I recently noticed that something I actually liked doing in certain cases (call super) is an anti-pattern. (<a href="http://en.wikipedia.org/wiki/Call_super" rel="nofollow">http://en.wikipedia.org/wiki/Call_super</a>)</p> <p>So my question is:</p> <p>How to do the following thing (a basic thing that most of us need, add some details to an object). I'll just add a new element to an array that is hold in an object var:</p> <pre><code> &lt;?php class A { // bla bla bla public function __construct() { $this-&gt;_data['newDetail'] = "Ipiicaei"; } } class B extends A { // bla bla bla // Override constructor, I need to add one more detail for this class public function __construct() { parent::__construct(); $this-&gt;_data['newDetailSubcls'] = "Something"; } } </code></pre> <p>Now... if I don't call the parent class constructor to add the first element, I have 2 possibilities:</p> <ol> <li><p>In each subclass add the part of code that the parent is normally doing, and remove it from parent. So if I extend it with 999 classes I'll duplicate 999*lines in parent. Sounds bad to me.</p></li> <li><p>Call a method from parent that is implemented in child (template method pattern, what they recommend). So if I need for only one class to add that, and the rest of 998 to behave exactly like the parent, in each of them I add an empty function. This also sounds bad to me.</p></li> </ol> <p>Bear in mind that my example is simple (that's how an example should be), but the parent class and/or subclass might do complicated things.</p> <p>I can see reasons why call super may be bad in some situations. But in this one seems ok to me.</p> <p>So... how would you approach? Ignore that call super is an anti-pattern and do as I do (or used to do if it turns out my way is bad)? Or... how?</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