PHP魔术方法-__get和__set在phpMVC框架serviceFactory中不起作用



我在index.php中创建了一个serviceFactory实例,它只是在自己中获取/存储(私有)变量。但是,由于某些原因,__get和__set魔术方法不起作用。在索引中执行var_dump($serviceFactory->语言)将返回false。当我创建serviceFactory的实例时,我将$router实例传递给$serviceFactory构造函数。路由器正在工作(否则它将不会显示控制器或视图),但由于某种原因,当我试图从$serviceFactory实例中__get语言时,它返回false,我不知道为什么。

index.php

//create an instance of serviceFactory
$serviceFactory = new serviceFactory($router);
var_dump($serviceFactory->language);

服务工厂

class serviceFactory {
    private $data = array();
    public function __construct($router) { //store the router data
        $data['language'] = $router->getKey('language');
        $data['class'] = $router->getKey('className');
        $data['method'] = $router->getKey('method');
        $data['arg'] = $router->getKey('arg');
    }
    public function __set($key, $val) {
        $this->data[$key] = $val;
    }
    public function __get($key) {
        if(isset($this->data[$key])) {
            return $this->data[$key];
        }
        else {
            return false;
        }
    }
}

很简单,您在处理实例时犯了一个常见的错误:

    $data['language'] = $router->getKey('language');
    $data['class'] = $router->getKey('className');
    $data['method'] = $router->getKey('method');
    $data['arg'] = $router->getKey('arg');

应该都是吗

    $this->data['language'] = $router->getKey('language');
    $this->data['class'] = $router->getKey('className');
    $this->data['method'] = $router->getKey('method');
    $this->data['arg'] = $router->getKey('arg');

相关内容

  • 没有找到相关文章

最新更新