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

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


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:

<?phpclass foo {     protected function bar($param){        echo $param;    }}$r = new ReflectionMethod('foo', 'bar');$r->setAccessible(true);$r->invoke(new foo(), "Hello World");


That's the point of OOP - encapsulation:

Private

Only can be used inside the class. Not inherited by child classes.

Protected

Only can be used inside the class and child classes. Inherited by child classes.

Public

Can be used anywhere. Inherited by child classes.

If you still want to trigger that function outside, you can declare a public method that triggers your protected method:

protected function b(){}public function a(){  $this->b() ;  //etc}


You can override this class with another where you make this public.

class cExample2 extends cExample {  public function funExample(){    return parent::funExample()  }}

(note this won't work with private members)

But the idea of private and protected members is to NOT BE called from outside.