cgm225 Posted August 17, 2008 Share Posted August 17, 2008 I have two pieces of code that are the same with the exception of one word ("albums" versus "photos" in this example), and I want to know how to be turn the code into a function or class so I only need to include it once? I am having problems with syntax because those words do not always "stand alone" in the code, but are sometimes part of a camelcase value, etc. Here is the code... Here it is used for "albums":: //Adds total number of entries to the registry $this->registry->set('totalEntries', $albums->getDataCount()); //Includes/instantiates class to specify number displayed per page require_once $this->pageDir . '/NumberDisplayed.php5'; $numberDisplayed = new NumberDisplayed('albums', 4); //Adds numberDisplayed per page variable to the registry $numberDisplayed = $numberDisplayed->getNumberDisplayed(); $this->registry->set('albumsDisplayed', $numberDisplayed); Here it is used for "photos":: //Adds album directory and total number of photos to the registry $this->registry->set('totalEntries', $photos->getDataCount()); //Includes/instantiates class to specify number displayed per page require_once $this->pageDir . '/NumberDisplayed.php5'; $numberDisplayed = new NumberDisplayed('photos', 4); //Adds numberDisplayed per page variable to the registry $numberDisplayed = $numberDisplayed->getNumberDisplayed(); $this->registry->set('photosDisplayed', $numberDisplayed); Any ideas on how to consolidate this code? Thanks in advance! Link to comment https://forums.phpfreaks.com/topic/120066-consolidating-redundant-code-how-to-make-function-or-class/ Share on other sites More sharing options...
Mchl Posted August 17, 2008 Share Posted August 17, 2008 That's a hackish solution, that certainly could and should be done better: function addTotalToRegistry($what) { $this->registry->set('totalEntries', $$what->getDataCount()); //Includes/instantiates class to specify number displayed per page require_once $this->pageDir . '/NumberDisplayed.php5'; $numberDisplayed = new NumberDisplayed($what, 4); //Adds numberDisplayed per page variable to the registry $numberDisplayed = $numberDisplayed->getNumberDisplayed(); $this->registry->set($what.'Displayed', $numberDisplayed); } Link to comment https://forums.phpfreaks.com/topic/120066-consolidating-redundant-code-how-to-make-function-or-class/#findComment-618517 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.