Skip to content

Instantly share code, notes, and snippets.

@soyoes
Created June 5, 2017 04:02
Show Gist options
  • Save soyoes/5e1f9f0c64d95883c76a293811754c6b to your computer and use it in GitHub Desktop.
Save soyoes/5e1f9f0c64d95883c76a293811754c6b to your computer and use it in GitHub Desktop.
<?php
trait DynamicDefinition {
public function __call($name, $args) {
if (is_callable($this->$name)) {
return call_user_func($this->$name, $args);
}
else {
throw new \RuntimeException("Method {$name} does not exist");
}
}
public function __set($name, $value) {
$this->$name = is_callable($value)?
$value->bindTo($this, $this):
$value;
}
}
class Foo {
use DynamicDefinition;
private $privateValue = 'I am private';
}
$foo = new Foo;
$foo->bar = function() {
return $this->privateValue;
};
// prints 'I am private'
print $foo->bar();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment