Is it really that wrong not using setters and getters?

前端 未结 7 904
谎友^
谎友^ 2020-12-03 07:51

I\'m kind of new in PHP. For some reason in other types of programming languages like JAVA I have no problem with using setters and getters for every single variable, but wh

7条回答
  •  再見小時候
    2020-12-03 08:34

    There is a way to emulate get/set without actually using get/set function class, so your code remains tidy:

    $person->name = 'bob';
    echo $person->name;
    

    Take a look at this class I have coded.

    Typically, when using this class, you would declare all your properties protected (or private). In the event where you'd want to add a behaviour on a property, say strtolower() + ucfirst() on the "name" property, all you'd need to do is declare a protected set_name() function in your class and the behavior should get picked up automatically. Same can be accomplished with get_name().

    // Somewhere in your class (that extends my class).
    protected function set_name($value) { $this->name = ucfirst(strtolower($value)); }
    //
    
    // Now it would store ucfirst(strtolower('bob')) automatically.
    $person->name = 'bob';
    

    P.S. Another cool thing is you can make up non-existing fields such as

    echo $person->full_name;
    

    without having such fields (as long as there is a get_full_name() function).

提交回复
热议问题