Page 1 of 1

"wrapper" functions

Posted: Fri Mar 16, 2012 8:00 am
by social_experiment
Lately i've been looking at some code i created and i noticed the following

Code: Select all

<?php
 class A {
     //
     protected function _doSomething()
     {
          // some code
     }
    
     //
     public function doSomething()
     {
         $this->_doSomething();
     }

 }
?>
The purpose for this is that if i extend class A i would use doSomething() instead of _doSomething() or even if class A isn't extended. This seems to correspond with what i read on wikipedia about the subject:
Wikipedia wrote: A wrapper function is a function in a computer program whose main purpose is to call a second function with little or no additional computation.
I have 2 questions about this:

1. What determines the use of a wrapper function? If you create a wrapper function for each protected method this would increase the amount of code you have to check / work through at a later stage.
2. Setting the method to protected stops it from being used outside the class but inside the class, what is a better option: to wrap the protected method or use it directly (throughout the class and any classes extended from the innitial class)?

Re: "wrapper" functions

Posted: Fri Mar 16, 2012 7:28 pm
by Christopher
I use this (and see this) most of the time to allow a Child class to provide functionality to a Parent class in a formal way. Like this:

Code: Select all

class A {
     abstract function _doSomething() {}
 
     public function doSomething()
     {
          // some code
         $this->_doSomething();
          // some code
     }
}

class B extends A {
     protected function _doSomething()
     {
          // code to be used by A
     }
}

$b = new B();
$b->doSomething();
This allows you to reduce duplicating code in child classes by requiring them to only implement the unique part of the code.

Re: "wrapper" functions

Posted: Sat Mar 17, 2012 11:47 am
by kon
For example PHP have many string functions that don’t always follow the same logic in their names (and moreover many mb functions) , to create a class with static methods (having all the same logic in their names) calling those would be a wrapper.