Search code examples
phpoopinheritancevisibilityencapsulation

Encapsulating and inheriting methods


I'm wondering if it's possible to encapsulate the methods of a class, but then expose them within a consuming class. For example (JFTR, I know this code is wrong)

class Consumer{
        public function __construct($obj){
            $this->obj = $obj;
            }

        public function doCommand(){
            $this->obj->command();
            }
        }

     class Consumed{
         //I would make the constructor private, but to save space...
         public function __construct(){}
         private function command(){
             echo "Executing command in the context of the Consumer";
             }
         }

     $consumer = new Consumer(new Consumed);
     $consumer->doCommand();

     //just to reiterate, I know this throws an error

Ultimately, I want to be able to make components that cannot be directly referenced outside the context of a single controlling class.


Solution

  • Sure it can, just make those methods protected, not private and have Consumed extend from Consumer. I'm not sure about the benefits though.