php - 如何使用魔术方法(__get 和 __set)访问多个属性?

标签 php magic-methods

我最近研究了魔术方法,__get__set,并且想知道如何实际设置和获取类中的多个属性。

我知道它仅适用于一个变量或数组,但我不确定是否可以访问多个变量。

有谁可以帮我解释一下吗?

class myMagic2 {
    public $data;
    public $name;
    public $age;

    public function __set($item, $value) {
        $this->item = $value;
    }

    public function __get($item){
        return $this->item;
    }
}

有没有办法访问所有变量($data$name$age)?

最佳答案

当我从事项目时,我总是有这些方法:

public function __set($name, $value) 
{
    //see if there exists a extra setter method: setName()
    $method = 'set' . ucfirst($name);
    if(!method_exists($this, $method))
    {
        //if there is no setter, receive all public/protected vars and set the correct one if found
        $vars = $this->vars;
        if(array_search("_" . $name, $vars) !== FALSE)
            $this->{"_" . $name} = $value;
    } else
        $this->$method($value); //call the setter with the value
}

public function __get($name) 
{
    //see if there is an extra getter method: getName()
    $method = 'get' . ucfirst($name);
    if(!method_exists($this, $method)) 
    {
        //if there is no getter, receive all public/protected vars and return the correct one if found
        $vars = $this->vars;
        if(array_search("_" . $name, $vars) !== FALSE)
            return $this->{"_" . $name};
    } else
        return $this->$method(); //call the getter
    return null;
}

public function getVars()
{
    if(!$this->_vars)
    {
        $reflect = new ReflectionClass($this);
        $this->_vars = array();
        foreach($reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED) as $var)
        {
            $this->_vars[] = $var->name;
        }
    }
    return $this->_vars;
}

因此,如果我想在写入/返回之前操作它们,我可以自由地为属性创建额外的 setter/getter。如果属性不存在 setter/getter,它将回退到属性本身。使用 getVars() 方法,您可以从类中接收所有公共(public)和 protected 属性。

我的类属性总是用下划线定义,因此您可能应该更改它。

关于php - 如何使用魔术方法(__get 和 __set)访问多个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704038/

相关文章:

php - 对二维数组使用神奇的 __set() 方法

PHP:5.2.x 的 __callStatic 替代方案

javascript - 如何删除 :hover from element when suddenly browser window lost focus?

Python __index__ 特殊方法

php - 关于继承的 PHP 魔术方法 __get 和 __set

javascript - 在 JavaScript 中访问 HTML 元素

php - 你如何在 symfony2 的表单类中隐藏标签?

PHP - preg_match 和 "Unknown modifier"错误

php - 如何在 PHP 中只执行一次代码块?

php - 嵌套查询不起作用