-1

I apologize if this is duplicate Question. I have a protected function. For example.

protected function example(){
//some code
}

and i would like to access this function from outside the class. And i came up with the following.

public function returnMyFunction(){
  return $this->example();

}

What i would like to know if this is a correct way to do this. Thank you!

P.S I forgot to mention that i came up with that because in zend framework 2 i cannot extend the class that this function is in since the class i am calling it from is extending another

dixromos98
  • 756
  • 5
  • 18
  • Perhaps this will help: http://stackoverflow.com/questions/4361553/php-public-private-protected – Robbert Apr 29 '14 at 14:48
  • 1
    What's the purpose of protected then? – ElmoVanKielmo Apr 29 '14 at 14:51
  • Yes well that is what i want to know. If by doing that the protected purpose is lost. I forgot to mention that i came up with that because in zend framework 2 i cannot extend the class that this function is in since the class i am calling it from is extending another – dixromos98 Apr 29 '14 at 14:53

1 Answers1

1

Actually a protected method is protected because it is not intended to be accessed outside the class and its childs. Summary:

The intention for private methods is that they will never be accessed from outside the class.
The intention for protected ones, is that they will enver be accessed from outside the class hierarchy (declaring class and its descendants). The intention for public methods is that they will be accessed from anywhere.

So, if you want to access the method outside a class, you should declare what you are declaring: an intermediate method (perhaps the intermediate public method performs a pre/post processing of the protected method). Another alternative to access it exceptionally (it's a hack! if you want to allow regular access, make it public instead) is to use Reflection (setting accessible = true), althought it is a bit slow.

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87