I have a protected function that is defined within a certain class. I want to be able to call this protected function outside of the class within another function. Is this possible and if so how may I achieve it
class cExample{ protected function funExample(){ //functional code goes here return $someVar }//end of function }//end of class function outsideFunction(){ //Calls funExample(); }
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
Here is the correct answer: We can use bind() or bindTo methods of Closure class to access private/protected data of some class, for example: class MyClass { protected $variable = 'I am protected variable!
You can't. That'd defeat the purpose of having a protected function in the first place. You could have a public method which invokes the protected method on your behalf, but then why have a protected method to begin with?
Yes, the protected method of a superclass can be overridden by a subclass.
Technically, it is possible to invoke private and protected methods using the reflection API. However, 99% of the time doing so is a really bad idea. If you can modify the class, then the correct solution is probably to just make the method public. After all, if you need to access it outside the class, that defeats the point of marking it protected.
Here's a quick reflection example, in case this is one of the very few situations where it's really necessary:
<?php class foo { protected function bar($param){ echo $param; } } $r = new ReflectionMethod('foo', 'bar'); $r->setAccessible(true); $r->invoke(new foo(), "Hello World");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With