PHP Magic Methods - __get and __set not working in php MVC framework serviceFactory

877 views Asked by At

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

There are 1 answers

1
Dimitri Mostrey On BEST ANSWER

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');