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.
<?php
class SomeClass
{
/**
*
*/
protected function _retrieveName()
{
// code
return $name;
}
/**
*
*/
protected function _displayName()
{
// I need the name, which function do i use to get it?
}
/**
* Wrapper function
*/
public function getName()
{
return $this->_retrieveName();
}
}
?>
_retrieveName() is a protected method, getName() acts as a wrapper function for the protected method. As per my example, if i need to get the name and i want to use an existing function, which one of the two would i use? My initial thought would be to use the protected method directly in the class wherever i need its functionality and the public function would be used outside the 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
If all getName() does is call a protected method then I wouldn't bother with the protected method at all. It's just (a tiny bit) extra overhead for absolutely no gain. You don't have to create some artificial barrier between public methods and protected methods: let the functionality and requirements dictate where code is and how visible it needs to be.
For the general case, what do I do... In the general case all the methods have different, even if slightly, behavior. There shouldn't even be a choice to make in the first place. And I say that as the conceptual "I think that's how my code works" answer - I don't think I've ever had this problem before.
The only reason I can think of to call one or the other is that calling getName() has the overhead of an extra function call. My concern with this interface is that whichever you pick, it is possible in the future that some code will get added to getName(). That will make the two methods different. Then there is a 50/50 chance that internal calls to one or the other may be to the wrong method.
requinix wrote:I don't think I've ever had this problem before.
I've actually be using this approach for a while because i thought that using a wrapper method was a better alternative than to using a function 'directly';
Christopher wrote: My concern with this interface is that whichever you pick, it is possible in the future that some code will get added to getName().
Ah yes i hadn't taken this into account because most of the time the protected method would have a specific purpose and rarely would that purpose change but it is definitely something i'll take into account in future projects
“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