Dynamically add a private property to an object

后端 未结 4 1461
感动是毒
感动是毒 2020-12-11 19:40

I have a class:

class Foo {
    // Accept an assoc array and appends its indexes to the object as property
    public function extend($values){
        forea         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 19:58

    Here is an accessor based approach:

    class Extendible
    {
        private $properties;
    
        public function extend(array $properties)
        {
            foreach ($properties as $name => $value) {
                $this->properties[$name] = $value;
            }
        }
    
        public function __call($method, $parameters)
        {
            $accessor = substr($method, 0, 3);
            $property = lcfirst(substr($method, 3));
            if (($accessor !== 'get' && $accessor !== 'set')
                    || !isset($this->properties[$property])) {
                throw new Exception('No such method!');
            }
            switch ($accessor) {
                case 'get':
                    return $this->getProperty($property);
                    break;
                case 'set':
                    return $this->setProperty($property, $parameters[0]);
                    break;
            }
        }
    
        private function getProperty($name)
        {
            return $this->properties[$name];
        }
    
        private function setProperty($name, $value)
        {
            $this->properties[$name] = $value;
            return $this;
        }
    }
    

    Demo:

    try {
        $x = new Extendible();
        $x->extend(array('foo' => 'bar'));
        echo $x->getFoo(), PHP_EOL; // Shows 'bar'
        $x->setFoo('baz');
        echo $x->getFoo(), PHP_EOL; // Shows 'baz'
        echo $x->getQuux(), PHP_EOL; // Throws Exception
    } catch (Exception $e) {
        echo 'Error: ', $e->getMessage(), PHP_EOL;
    }
    

提交回复
热议问题