Skip to content

Instantly share code, notes, and snippets.

@webmozart
Forked from beberlei/symfony-form-config4.php
Created February 6, 2011 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webmozart/813505 to your computer and use it in GitHub Desktop.
Save webmozart/813505 to your computer and use it in GitHub Desktop.
Using a static OptionSupport class that automatically writes options into properties AND fields extend it.
+ Options are set in the very beginning of the constructor
+ Concise
+ Error if option is not supported
+ Everything is a property, no special treatment of options
+ Good performance
+ Static options can be hidden from public access
- Private properties wouldn't work, access not allowed from parent classes.
<?php
class Thing extends OptionSupport
{
protected static $options = array('required');
protected static $requiredOptions = array('required');
protected $required = false; // default value is false
public function __construct(array $options = array())
{
self::initialize($this, $options);
}
public function getRequired() { return $this->required; }
}
class OptionSupport
{
static public function initialize($obj, $options)
{
// validate here and such
foreach ($options AS $k => $v) {
$obj->$k = $v;
}
}
}
// Ugly: You have to respell all the previous options
class OtherThing extends Thing
{
public static $options = array('required', 'newoption');
public static $requiredOptions = array('required', 'newoption');
protected $newoptions;
public function getNewOptions()
{
return $this->newoptions;
}
}
$o = new OtherThing(array('required' => true, 'newoptions' => 'asdf'));
echo "NewOptions: " . $o->getNewOptions() . "\n";
echo "REquired: " . $o->getRequired() . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment