Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As said, if you are going to extend a class later you can always change it then.</p> <p>But if you can avoid to use inheritance you should. It is better to use other patterns when designing, if possible. </p> <p>Basically what to do is favor composition over inheritance and program to interfaces, not to implementations. </p> <p>If you let classes just have one tightly defined purpose than you can composit objects instead of letting them inherit each other. If you use interfaces rather then inheritance you will most likley define small and effective interfaces. Then you will see that inheritance will reduce and therefore the need of protected will reduce to. </p> <p>Example</p> <pre><code>interface sound { public function makeSound(); } class bark implements sound{ public function makeSound() { return "Bark!!!"; } } class mew implements sound{ public function makeSound() { return "Mewmew!!!"; } } class forLeggedAnimal { private $sound; public function forLeggedAnimal($sound){ $this-&gt;sound = $sound; } public function eat(){ echo $this-&gt;sound-&gt;makeSound(); } } $cat = new forLeggedAnimal(new mew()); $dog = new forLeggedAnimal(new bark()); </code></pre> <p>I know this far from a perfect example. But it illustrates the technique and you can use this in many ways. For instance you can combine this with different creational patterns to build cats and dogs, it may not be so wise to have to know if a cat barks or mews.. But anyway.. it differs from having to make a base class and then extending it with a cat and a dog, and therefor have to make the "sound" method protected or overriding the public eat method</p> <p>/Peter </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