<?php
class BaseObject extends stdClass
{
public function __call($method, $args = array())
{
return call_user_func_array($this->$method, $args); //call closure
}
}
/**
* Create className instance add getIncrementedAge, getName behaviours
*
* @param string $className
* @param integer $age
* @param string $name
* @return object same type as $className
*/
function Type()
{
$props = func_get_args();
$className = array_shift($props);//classname should be first
$refFunction = new ReflectionFunction('Type');
$props = array_combine(// make dictionary from function arg names (from phpdoc) and function arguments
array_map(//extract variable names from phpdoc @param line
function ($docString) { //search variable name and return it
preg_match('/\$(\w+)/',$docString, $data);
return $data[1];
},
array_filter( //make lines array from phpdoc, filtering all except strings with @param and skip string with $className
explode("\n", $refFunction->getDocComment()),
function ($line)
{
return strpos($line, 'param') > 0 && strpos($line, '$className' ) < 1 ;
}
)
),
$props
);
$ob = new $className();
foreach ( $props as $name => $value)
$ob->$name = $value;
$ob->getName = function () use($ob)
{
return $ob->name;
};
$ob->getIncrementedAge = function ($inc =1) use($ob)
{
return $ob->age + $inc;
};
return $ob;
}
$cd = Type('BaseObject', 10,'cd');
$stas = Type('BaseObject', 20, 'stas');
var_dump($cd->getName());
var_dump($cd->getIncrementedAge(2));
var_dump($stas->getName());
var_dump($stas->getIncrementedAge(3));
Результат
php test.php
string(2) "cd"
int(12)
string(4) "stas"
int(23)
No comments:
Post a Comment