Getter and Setter?

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

    Well, PHP does have magic methods __get, __set, __isset & __unset, which is always a start. Alas proper (get it?) OO properties is more than magic methods. The main problem with PHP's implementation is that magic methods are called for all inaccessible properties. Which means you have to Repeat Yourself (eg. by calling property_exists()) in the magic methods when determining if name is actually a property of your object. And you can't really solve this general problem with a base class unless all your classes inherit from ie. ClassWithProperties, since PHP lacks multiple inheritance.

    In contrast, Python new style classes gives you property(), which lets you explicitly define all your properties. C# has special syntax.

    http://en.wikipedia.org/wiki/Property_(programming)

提交回复
热议问题