Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I/How to... call a protected function outside of a class in PHP

Tags:

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();  } 
like image 861
Terry Hoverter Avatar asked Jun 18 '13 16:06

Terry Hoverter


People also ask

How do you access protected methods outside a class?

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.

How can we access protected variable outside class in PHP?

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!

Can we call protected function?

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?

Can you override a protected method PHP?

Yes, the protected method of a superclass can be overridden by a subclass.


1 Answers

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"); 
like image 174
Peter Geer Avatar answered Sep 29 '22 09:09

Peter Geer