我正在创建一个允许用户使用自己的类扩展系统的小系统。
Class Core {
static $confArray;
static $extendArray;
protected static $instance;
public function read($name)
{
return self::$confArray[$name];
}
public function put($name, $value)
{
self::$confArray[$name] = $value;
}
public function extend($function, $handler, $args=null){
self::$extendArray[$function] = new $handler($args);
}
public function __call($method, $args){
return self::$extendArray[$method];
}
public static function getInstance()
{
if (!isset(self::$instance))
{
$object =__CLASS__;
self::$instance= new $object;
}
return self::$instance;
}
}
有了这个,现在用户可以从这样的类中注册一个简单的扩展名:
class WorkersTest{
function isWorking($who){
echo "$who is working";
}
function isNotWorking($who){
echo "$who is not working";
}
}
要调用函数(isworking / isNotWorking),程序员需要通过以下方式注册test
类:
Core::getInstance->extend("worker","WorkersTest");
然后现在可以通过以下方式调用:
Core::getInstance->worker()->isWorking("George");
这很完美。我的问题是我如何删除电话中的()
(不要担心为什么)并且有:
Core::getInstance->worker->isWorking("George");
有可能吗?
答案 0 :(得分:3)
您可以使用魔术__get()
方法,就像__call()
:
public function __get($name)
{
return $this->$name();
}
答案 1 :(得分:2)
尝试覆盖magic __get()方法以返回您需要的内容:
Class Core {
// (...)
public function __get($name) {
if (isset( self::$extendArray[$function] )) {
return $this->$name();
}
//if there is no function registered under named "$name"
//throwing Exception is by design better, as @scragar suggested
throw new Exception("No function registered under named {$name}");
//return NULL;
}
}