Getter and Setter?

前端 未结 15 838
南方客
南方客 2020-11-22 16:47

I\'m not a PHP developer, so I\'m wondering if in PHP is more popular to use explicit getter/setters, in a pure OOP style, with private fields (the way I like):



        
15条回答
  •  盖世英雄少女心
    2020-11-22 17:30

    If you preffer to use the __call function, you can use this method. It works with

    • GET => $this->property()
    • SET => $this->property($value)
    • GET => $this->getProperty()
    • SET => $this->setProperty($value)

    kalsdas

    public function __call($name, $arguments) {
    
        //Getting and setting with $this->property($optional);
    
        if (property_exists(get_class($this), $name)) {
    
    
            //Always set the value if a parameter is passed
            if (count($arguments) == 1) {
                /* set */
                $this->$name = $arguments[0];
            } else if (count($arguments) > 1) {
                throw new \Exception("Setter for $name only accepts one parameter.");
            }
    
            //Always return the value (Even on the set)
            return $this->$name;
        }
    
        //If it doesn't chech if its a normal old type setter ot getter
        //Getting and setting with $this->getProperty($optional);
        //Getting and setting with $this->setProperty($optional);
        $prefix = substr($name, 0, 3);
        $property = strtolower($name[3]) . substr($name, 4);
        switch ($prefix) {
            case 'get':
                return $this->$property;
                break;
            case 'set':
                //Always set the value if a parameter is passed
                if (count($arguments) != 1) {
                    throw new \Exception("Setter for $name requires exactly one parameter.");
                }
                $this->$property = $arguments[0];
                //Always return the value (Even on the set)
                return $this->$name;
            default:
                throw new \Exception("Property $name doesn't exist.");
                break;
        }
    }
    

提交回复
热议问题