2

Is there any possibility to reduce the access level of a function in a derived class in PHP?

example (... means more code)

class foo
{
  public function myFunction() { ... }
  public function myOtherFunction() { ... }
}

class bar extends foo
{
  private function myFunction() { ... }
}

Now I should'nt be able to call MyFunc ion a bar object. But doing it this way doesn't seem to be valid in PHP. Any other way? I know I could implement an empty function but I don't want to expose the function in the interface at all.

hakre
  • 193,403
  • 52
  • 435
  • 836
inquam
  • 12,664
  • 15
  • 61
  • 101

1 Answers1

4

Its not valid in OOP anyway. If you implement a public method, you promise, that this class and all children provides this functionality. To remove a public method means, that you break your promises ;) Because all public methods and properties define the interface of the class and breaking an interface is never a good idea.

Without any clearer information about what you are going to do I suggest to just throw an exception, something like "Not supported".

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • The thought was that I have an abstract class that has a function called registerObject() and then I have a class extending this and have a function called registerForm() that would actually just call parent::registerObject() but would be a more fitting name for the object in question. But you are right this is bad practise when I think about it :)... I should probably make a protected function registerObject() and then having the public function registerForm() in the derived class and so on. – inquam Dec 14 '10 at 10:36
  • We have a class OurException extends Exception . We have 2 ways in which to create an instance of OurException. Because of PHPs innate inability to overload __construct in an elegant way, we would like to to create 2 static methods, ie. OurException::newA and OurException::newB (from my research this appears a fairly standard way to fudge overloading). But we dont then want people using "new OurException" so would like to make __construct protected or private. This is not possible because Exception __construct is public. – Pancho May 26 '16 at 14:52
  • ...continued. Sadly it does not make sense in our context to throw an Exception "Not Supported" when an Exception is in the process of being thrown. If PHP could reliably overload a constructor then it would make much more sense adhering to the OOP "promise" you refer to above. However, without clean overloading, the inability to "reduce accessibility to __construct" is in our context highly problematic ...and I'm really not sure how to get around the problem :( – Pancho May 26 '16 at 14:57