Skip to content

Instantly share code, notes, and snippets.

@hendrik-weiler
Created March 26, 2012 11:26
Show Gist options
  • Save hendrik-weiler/2204510 to your computer and use it in GitHub Desktop.
Save hendrik-weiler/2204510 to your computer and use it in GitHub Desktop.
extend php classes like in javascript
<?php
class ExtendClass
{
public function __call($name,$args)
{
if(isset($this->$name) && is_callable($this->$name))
return call_user_func_array($this->$name, $args);
else
throw new Exception("Method: " . $name . " doenst exist.");
}
public function __invoke($functions)
{
foreach ($functions as $name => $func)
{
$this->$name = $func;
}
}
public function __set($name, $value)
{
$this->$name = $value;
}
public function __get($name)
{
if(isset($this->$name))
return $this->$name;
else
throw new Exception("Property does not exist or is private/protected");
}
}
class Test extends ExtendClass
{
public $x = 5;
public function doSomething() {
foreach ($this as $value) {
if(!is_object($value))
print $value . '<br />';
}
}
}
$asd = new Test;
$asd(array(
'addieren' => function($x) use(&$asd) {
$asd->x += $x;
return $asd->x;
},
'nummer' => 0,
'testobj' => new Test,
'extendtest' => function() use (&$asd) {
$asd->testobj(array(
'testfunc' => function() {
print 'im a test';
}
));
}
));
print $asd->addieren(5);
print '<br>';
print $asd->addieren(5);
print '<br>';
print $asd->addieren(5);
print '<br>';
print $asd->addieren(5);
print '<br>';
$asd->extendtest();
$asd->testobj->testfunc();
$asd->doSomething();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment