Skip to content

Instantly share code, notes, and snippets.

@sheldon
Forked from phpwax/gist:4140042
Created November 24, 2012 17:03
Show Gist options
  • Save sheldon/4140527 to your computer and use it in GitHub Desktop.
Save sheldon/4140527 to your computer and use it in GitHub Desktop.
Trait for defaults and settings
<?php
trait StaticDefaults{
protected static $_defaults = [];
public function __get($key){
if(is_callable($func = self::$_defaults[$key])) return $func();
return $func;
}
static public function defaults($defaults){
self::$_defaults += $defaults;
}
}
trait ArrayConstruct{
public function __construct($s = []){
foreach($s as $k => $v) $this->$k = $v;
}
}
abstract class Model{
use StaticDefaults, ArrayConstruct;
}
class ExampleModel extends Model {
}
class Application{
function __construct(){
$this->configure();
}
public function configure(){
Model::defaults(["db"=>["host"=>"127.0.0.1", "username"=>"user", "password"=>"pass"]]);
}
public function run(){
$model = new ExampleModel; //default db
print_r($model->db);
$model2 = new ExampleModel(["db"=>["host"=>"8.8.8.8", "username"=>"google", "password"=>"dns"]]); //overriden db
print_r($model2->db);
}
}
$app = new Application;
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment