0

I created an instance of serviceFactory in index.php which simply gets/stores (private) variables in itself. But, the __get and __set magic methods for some reason are not working. Doing a var_dump($serviceFactory->language) in the index returns false. When I create an instance of serviceFactory, I pass the $router instance to the $serviceFactory constructor. The router is working (otherwise it would not display controller or view), but for some reason, when I try to __get the language from the $serviceFactory instance, it returns false and I'm confused as to why.

index.php

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

serviceFactory

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;
        }
    }
}
4

1 回答 1

0

Simple, you've made a common mistake in working with instances:

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

should all be

    $this->data['language'] = $router->getKey('language');
    $this->data['class'] = $router->getKey('className');
    $this->data['method'] = $router->getKey('method');
    $this->data['arg'] = $router->getKey('arg');
于 2013-08-22T09:13:34.633 回答