Created
May 9, 2012 16:19
-
-
Save pateketrueke/2646134 to your computer and use it in GitHub Desktop.
Klass Implementation for PHP 5.4+
This file contains 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
<?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