"wrapper" functions

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

"wrapper" functions

Post 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)?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: "wrapper" functions

Post 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.
(#10850)
kon
Forum Newbie
Posts: 19
Joined: Sat Mar 03, 2012 5:43 am

Re: "wrapper" functions

Post 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.
Post Reply