So let's say I have classes called parent and child, which will be then used from PHP file called caller.php
class Child extends Parent { } class Parent { public function parentMethod(){ } } caller.php
PREVENTED:
$child = new Child(); $child->parentMethod(); ALLOWED:
$parent = new Parent(); $parent->parentMethod(); I want to prevent calling parentMethod like this. But if I created Parent object I want to be able to call the parentMethod. Is there some way that I can use to hide this method from being public in Child class, but still allowing parent object to call this method publicly?
Only solution I have come up with so far is making those methods protected and then creating an other class that would extend parent and then have public method for each function that it needs, but that doesn't sound very smart.
publicso you defined those methods as visible everywhere. If you want to hide parent methods from child classes, useprivate- but then such methods won't be seen anywhere, but that class itself.protectedisn't enough. It means visibility everywhere, including child classes. To hide method from childs, useprivateextendsanother, then that class is for all intends and purposes identical to the parent class, but possibly does more or does some things different internally. But it must still be able to exactly replace the parent class in any instance where the parent class could be used. That's the Liskov substitution principle: en.wikipedia.org/wiki/SOLID. This is bad OOP design.