Getter and Setter?

前端 未结 15 827
南方客
南方客 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:34

    Validating + Formatting/Deriving Values

    Setters let you to validate data and getters let you format or derive data. Objects allow you to encapsulate data and its validation and formatting code into a neat package that encourages DRY.

    For example, consider the following simple class that contains a birth date.

    class BirthDate {
    
        private $birth_date;
    
        public function getBirthDate($format='Y-m-d') {
            //format $birth_date ...
            //$birth_date = ...
            return $birth_date;
        }
    
        public function setBirthDate($birth_date) {                   
            //if($birth_date is not valid) throw an exception ...          
            $this->birth_date = $birth_date;
        }
    
        public function getAge() {
            //calculate age ...
            return $age;
        }
    
        public function getDaysUntilBirthday() {
            //calculate days until birth days
            return $days;
        }
    }
    

    You'll want to validate that the value being set is

    • A valid date
    • Not in the future

    And you don't want to do this validation all over your application (or over multiple applications for that matter). Instead, it's easier to make the member variable protected or private (in order to make the setter the only access point) and to validate in the setter because then you'll know that the object contains a valid birth date no matter which part of the application the object came from and if you want to add more validation then you can add it in a single place.

    You might want to add multiple formatters that operate on the same member variable i.e. getAge() and getDaysUntilBirthday() and you might want to enforce a configurable format in getBirthDate() depending on locale. Therefore I prefer consistently accessing values via getters as opposed to mixing $date->getAge() with $date->birth_date.

    getters and setters are also useful when you extend objects. For example, suppose your application needed to allow 150+ year birth dates in some places but not in others. One way to solve the problem without repeating any code would be to extend the BirthDate object and put the additional validation in the setter.

    class LivingBirthDate extends BirthDate {
    
        public function setBirthDate($birth_date) {
            //if $birth_date is greater than 150 years throw an exception
            //else pass to parent's setter
            return parent::setBirthDate($birth_date);
        }
    }
    

提交回复
热议问题