Search code examples
phpfunctioncallprotected

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


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();

}

Solution

  • 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
    }