Memory App
Programming
 




Get magic method


<?php 
    class A {
        public function __get($var) {
            return 2;
        }
    }

    $a = new A();
    echo $a->foo; // outputs 2
With __get() method you can keep track of variables which are not defined inside the class.

<?php 
    class myController {

        private $_modelBroker = array();
        
        public function __get($var) {

            if (strstr($var, 'model')) {

                $modelKey = substr($var, 5);
                
                // variable is already registered or not
                if (in_array($modelKey, array_keys($this->_modelBroker))) {
                    return $this->_modelBroker[$modelKey];
                } else {
                    eval('$model = new Model_'.$modelKey.'();');
                    $this->_modelBroker[$modelKey] = $model;
                    return $model;
                }
            }
        }
    }

    class Model_Number {
        public $id = 123;
    }
    
    $controller = new myController();
    
    echo $controller->modelNumber->id; // Output 123
        // __get is called, because modelNumber is undefined
    
The function names bellow are magical in PHP classes.

__construct(), __destruct(),
__call(), __callStatic(), 
__get(), __set(), 
__isset(), __unset(), 
__sleep(), 
__wakeup(), 
__toString(), 
__invoke(), 
__set_state(), 
__clone()
__debugInfo() 
You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

Questions



Top Reference > Programming