Created
June 5, 2017 04:02
-
-
Save soyoes/5e1f9f0c64d95883c76a293811754c6b 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
<?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