Using __get() (magic) to emulate readonly properites and lazy-loading

后端 未结 4 985
北荒
北荒 2021-02-19 12:46

I\'m using __get() to make some of my properties \"dynamic\" (initialize them only when requested). These \"fake\" properties are stored inside a private array property, which I

4条回答
  •  日久生厌
    2021-02-19 12:53

    If your capitalization of the class names and the key names in $prop matched, you could do this:

    class Dummy {
        private $props = array(
            'Someobject' => false,
            //etc...
        );
    
        function __get($name){
            if(isset($this->props[$name])){
                if(!($this->props[$name] instanceof $name)) {
                    $this->props[$name] = new $name();
                }
    
                return $this->props[$name];
            }
    
            //trigger_error('property doesnt exist');
            //Make exceptions, not war
            throw new Exception('Property doesn\'t exist');     
        }
    }
    

    And even if the capitalization didn't match, as long as it followed the same pattern it could work. If the first letter was always capitalized you could use ucfirst() to get the class name.


    EDIT

    It's probably just better to use plain methods. Having a switch inside a getter, especially when the code executed for each thing you try to get is different, practically defeats the purpose of the getter, to save you from having to repeat code. Take the simple approach:

    class Something {
        private $props = array('Someobject' => false);
    
        public getSomeobject() {
            if(!($this->props['Someobject'] instanceof Someobject)) {
                //Instantiate and do extra stuff
            }
    
            return $this->props['Someobject'];
        }
    
        public getSomeOtherObject() {
            //etc..
        }
    }
    

提交回复
热议问题