Getter and Setter?

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

    In addition to the already great and respected answers in here, I would like to expand on PHP having no setters/getters.

    PHP does not have getter and setter syntax. It provides subclassed or magic methods to allow "hooking" and overriding the property lookup process, as pointed out by Dave.

    Magic allows us lazy programmers to do more with less code at a time at which we are actively engaged in a project and know it intimately, but usually at the expense of readability.

    Performance Every unnecessary function, that results from forcing a getter/setter-like code-architecture in PHP, involves its own memory stack-frame upon invocation and is wasting CPU cycles.

    Readability: The codebase incurs bloating code-lines, which impacts code-navigation as more LOC mean more scrolling,.

    Preference: Personally, as my rule of thumb, I take the failure of static code analysis as a sign to avoid going down the magical road as long as obvious long-term benefits elude me at that time.

    Fallacies:

    A common argument is readability. For instance that $someobject->width is easier to read than $someobject->width(). However unlike a planet's circumference or width, which can be assumed to be static, an object's instance such as $someobject, which requires a width function, likely takes a measurement of the object's instance width.
    Therefore readability increases mainly because of assertive naming-schemes and not by hiding the function away that outputs a given property-value.

    __get / __set uses:

    • pre-validation and pre-sanitation of property values

    • strings e.g.

      "
      some {mathsobj1->generatelatex} multi
      line text {mathsobj1->latexoutput}
      with lots of variables for {mathsobj1->generatelatex}
       some reason
      "
      

      In this case generatelatex would adhere to a naming scheme of actionname + methodname

    • special, obvious cases

      $dnastringobj->homeobox($one_rememberable_parameter)->gattaca->findrelated()
      $dnastringobj->homeobox($one_rememberable_parameter)->gttccaatttga->findrelated()
      

    Note: PHP chose not to implement getter/setter syntax. I am not claiming that getters/setter are generally bad.

提交回复
热议问题