I like using PHP classes to keep my code organized and easy to
maintain. I know that they consume more memory than simply using an
array or variable system, but if memory is an issue, I'd get more
memory. Saving time by coding in a maintainable fashion is more
important to me than upgrading a server. I've written a very generic,
flexible PHP class that I use in my PHP code to get and set variables
for use within the page.
The PHP Class
class generic {
var $vars;
function generic() { }
function get($var) {
return $this->vars[$var];
}
function set($key,$value) {
$this->vars[$key] = $value;
}
function load($array) {
if(is_array($array)) {
foreach($array as $key=>$value) {
$this->vars[$key] = $value;
}
}
}
function unload($vars = '') {
if($vars) {
if(is_array($vars)) {
foreach($vars as $var) {
unset($this->vars[$var]);
}
}
else {
unset($this->vars[$vars]);
}
}
else {
$this->vars = array();
}
}
function get_all() {
return $this->vars;
}
}
Simple Usage
$person = new generic();
$person->set('name','David');
$person->set('age','24');
$person->set('occupation','Programmer');
echo '<strong>Name:</strong> ',$person->get('name'),'';echo '<strong>Age:</strong> ',$person->get('age'),'';echo '<strong>Job:</strong> ',$person->get('occupation'),'';$person->unload('name');
$person->unload(array('age','occupation'));
Database Usage
$query = 'SELECT name,age,occupation FROM users WHERE user_id = 1';
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$user = new generic();
$user->load($row);
echo '</strong>Name:</strong> ',$user->get('name'),'';echo '</strong>Age:</strong> ',$user->get('age'),'';echo '</strong>Job:</strong> ',$user->get('occupation'),'';
Save To The Session, Retrieve From The Session
$_SESSION['person'] = $person->get_all();
$person = new generic();
$person->load($_SESSION['person']);
Let me know your thoughts on this type of class. Do you have any suggestions for improvement?