The wait is over for a way to add the functionality of a Javascript options object to PHP5.
I will forwarn that this post contains mostly code since I explained the benifits of this methodoly in my previous post on javascript option objects.
It is a bit different js options object in that it will only set options which had defaults supplied upon creation.
Example:
class Hello
{
var $defaultOptions = array('planet' => 'World', 'punctuation' => '!');
function __construct($options = array())
{
$this->options = new OptionsObject($this->defaultOptions);
$this->opts->setOptions($options);
}
function message()
{
return 'Hello ' . $this->opts->planet . $this->opts->punctuation;
}
}
// outputs 'Hello World!'
$a = new HelloPlanet();
print $a->message();
// outputs 'Hello Mars!'
$b = new HelloPlanet(array('planet' => 'Mars'));
print $b->message();
OptionsObject Code:
class OptionsObject
{
private $options;
public function __construct($options)
{
$this->options = $options;
}
public function isValidOption($name)
{
return array_key_exists($name, $this->options);
}
public function setOptions(array $options)
{
foreach($options as $key => $value)
{
if($this->isValidOption($key)) $this->options[$key] = $value;
}
}
public function __get($option)
{
return $this->options[$option];
}
}
RSS




















