What is the best way to auto generate getters and setters for a class in php?

泄露秘密 提交于 2019-12-03 06:50:39

With Eclipse go to Preferences -> PHP -> Editor -> Templates -> New and use something like this:

private $$${PropertyName};
${cursor}    
public function get${PropertyName}() 
{
  return $$this->${PropertyName};
}

public function set${PropertyName}($$value) 
{
  $$this->${PropertyName} = $$value;
}

To use the template type it's name and press ctrl+space - a context menu should also automatically appear when you type the name.

Have you looked at the __set and __get methods? Don't know if this is what you mean but the are automatically called whenever a class member is SET or Retrieved/Fetched/Accessed.

Zend Studio has a feature of automatic getter/setter generation.

I think the best way is to use the __set and __get with some string functions, Here let me show you.

class UserProfile
{
    public function __get($key)
    {
        if(isset($this->$key))
        {
            return $this->$key;
        }
    }

    public function __set($key,$val)
    {
        $this->cahnge($key,$val);
    }

    public function __call($key,$params)
    {
        if(substr("set",$key))
        {
            //Update
        }elseif(substr("get",$key))
        {
            //return
        }

        //Else Blah
    }

    private function change($key,$val)
    {
        if(isset($this->$key))
        {
            $this->$key = $val;
        }
    }
}

the __call() method will allow you to set with functions such as

$profile->setUsername('Robert Pitt'); as long as you substr the set/get and check for the rest of the string as a value of the class :)

another example

public function __call($method,$params = array())
{

    if(isset($params[0]) && is_string($params[0]))
    {
        $this->$method = $params[0];
    }
}

//....

$profile->username('Robert Pitt');

Theres more work to be done here

Maybe better sollution:

class base {

    protected $_vars = array();


    public function setVar($name, $value = null) {
        $this->_vars[$name] = $value;
    }

    public function getVar($name) {
        return isset($this->_vars[$name]) ? $this->_vars[$name] : null;
    }
}

And simply extend this class. Or also you can use __set and __get methods, but they are quite slower.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!