<?php
abstract class Base{
protected $funcs = [];
public function __call($name, $args) {
error_log("\t>>>Call [$name](". json_encode($args). ") \r\n",3, LOGFILE);
if (method_exists($this, $name)) {
return call_user_func_array($this->$name, $args);
} else if (isset($this->funcs[ $name ])) {
return call_user_func_array($this->funcs[ $name ], $args);
} else {
throw new Exception("Method <$name> is not accessible.");
}
}
/**
* @param array $args
*
* @example new Base(["field1"=>"value1", "field2"=>"value2"])
* if u need override __constructor, then use:
* __construct($args){
* ..
* parent::__construct($args);
* }
*/
public function __construct($args = []) {
$nameClass = get_class($this);
#region auto create methods 'hasField' for everyone field\property (if there exists getter or setter)
$properties = get_class_vars($nameClass);
$keys = array_keys($properties);
foreach ($keys AS $k) {
if ((method_exists($this, "set" . ucfirst($k)) || method_exists($this, "get" . ucfirst($k)))
&& (!method_exists($this, "has" . ucfirst($k) && !isset($this->funcs["has" . ucfirst($k)])))
) {
$v = &$this->$k;
$this->funcs["has" . ucfirst($k)] = function () use (&$v) { return !empty($v); };
}
}
#endregion
foreach ($args as $k => $v) {
if (property_exists($nameClass, $k)) {
$this->$k = $v;
}
}
}
}
class Test extends Base{
protected $field1;
public function setField1($v){$this->field1 = $v;}
public function getField1(){return $this->field1;}
}
$test = new Test();
$test->setField1(23423);
echo $test->hasField1();
preferences:
55.14 ms | 402 KiB | 5 Q