-
-
Save webmozart/813505 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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