Using __get() (magic) to emulate readonly properites and lazy-loading

后端 未结 4 984
北荒
北荒 2021-02-19 12:46

I\'m using __get() to make some of my properties \"dynamic\" (initialize them only when requested). These \"fake\" properties are stored inside a private array property, which I

4条回答
  •  甜味超标
    2021-02-19 13:12

    I'm using __get() to make some of my properties "dynamic" (initialize them only when requested). These "fake" properties are stored inside a private array property, which I'm checking inside __get.

    Anyway, do you think it's better idea to create methods for each of these proprties instead of doing it in a switch statement?

    The way you ask your question I don't think it is actually about what anybody thinks. To talk about thoughts, first of all it must be clear which problem you want to solve here.

    Both the magic _get as well as common getter methods help to provide the value. However, what you can not do in PHP is to create a read-only property.

    If you need to have a read-only property, you can only do that with the magic _get function in PHP so far (the alternative is in a RFC).

    If you are okay with accessor methods, and you are concerned about typing methods' code, use a better IDE that does that for you if you are really concerned about that writing aspect.

    If those properties just do not need to be concrete, you can keep them dynamic because a more concrete interface would be a useless detail and only make your code more complex than it needs to be and therefore violates common OO design principles.

    However, dynamic or magic can also be a sign that you do something wrong. And also hard to debug. So you really should know what you are doing. That needs that you make the problem you would like to solve more concrete because this heavily depends on the type of objects.

    And speed is something you should not test isolated, it does not give you good suggestions. Speed in your question sounds more like a drug ;) but taking that drug won't give you the power to decide wisely.

提交回复
热议问题