Skip to content

Instantly share code, notes, and snippets.

@pateketrueke
Created May 9, 2012 16:19
Show Gist options
  • Save pateketrueke/2646134 to your computer and use it in GitHub Desktop.
Save pateketrueke/2646134 to your computer and use it in GitHub Desktop.
Klass Implementation for PHP 5.4+
<?php
class Klass {
private $props = array();
public function __construct(array $params = array()) {
$this->props = $params;
}
public function __call($method, $arguments) {
if ($item = $this->$method) {
if ($item instanceof Closure) {
return call_user_func_array($item->bindTo($this), $arguments);
}
}
throw new Exception("Undefined method: $method");
}
public function __set($key, $val) {
$this->props[$key] = $val;
}
public function __get($key) {
if ( ! empty($this->props[$key])) {
return $this->props[$key];
}
throw new Exception("Undefined property: $key");
}
}
$foo = new Klass([
'x' => 'y',
'z' => function () {
echo $this->x;
},
]);
$foo->z();
$foo->z = function () {
return phpversion();
};
echo "\n", $foo->z();
#$foo->bar();
#echo $foo->candy;
#var_dump($foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment