This isn't really anything special, but I thought I would share because someone might find it interesting. You would use an options array when you want to dictate a class' behavior at times, but at other times you want to rely on default settings. Really, it's nothing more than a glorified optional parameter, but it allows you to save some space and it's a cleaner syntax (IMO). Any thoughts?
The options class:
Code: Select all
<?php
class VMClass {
// @var array $options - The generic options array for which extending classes should set default values
public $options = array();
/**
* Description: The setOptions method should be called in the constructor of an extending class
* @param array $options - The options array resets any default options present in the class
* @return - $this
*/
protected function setOptions($options) {
if (is_array($options)){
foreach ($options as $key => $value){
$this->options[$key] = $value;
}
$this->options = $this->arrayToObject($this->options);
}
return $this;
}
/**
* Description: Recursively returns an array as an object, for easier syntax
* Credit: Mithras @ http://us2.php.net/manual/en/language.t ... .php#85237
* @param array $array - The array to return as an object
* @return - The object converted from the array
*/
public function arrayToObject(array $array){
foreach ($array as $key => $value){
if (is_array($value)) $array[$key] = $this->arrayToObject($value);
}
return (object) $array;
}
}
?>Code: Select all
<?php
class TestClass extends VMClass {
//The default options settings
public $options = array(
'name' => array('first'=>'Fred',
'last'=>'Flintstone'),
'question' =>'How are you?',
'useQuestion' => TRUE
);
function __construct($options = null){
$this->setOptions($options);
}
public function greet($salutation){
echo $salutation.', '.$this->options->name->first.' '.$this->options->name->last.'. ';
if ($this->options->useQuestion) echo $this->options->question;
}
}
?>Code: Select all
<?php
include('vmclass.php');
include('testclass.php');
$options = array('question'=>'Que pasa?', 'useQuestion'=>TRUE);
$foo = new TestClass($options);
$foo->greet('Howdy');
$foo->options->name->first = 'Wilma';
$foo->options->useQuestion = FALSE;
$foo->greet('Bonjour');
?>