What is the point of OOP visibility in PHP when Closures and Reflections are available?

前端 未结 2 1497
耶瑟儿~
耶瑟儿~ 2021-02-13 02:45

Consider this code here:

final class TinkerWithMe {
    protected $key1 = 19;
    private $key2 = 88;
}

$class = new TinkerWithMe();

$getKeys = function() {
           


        
2条回答
  •  抹茶落季
    2021-02-13 03:36

    Visibility modifiers aren't iron clad protection or ensure any sort of security or anything of that sort. They're markers for how a piece of code is intended to be used.

    When writing a piece of code like a class, other pieces of code are going to couple with it; meaning you will write other code that calls methods of that class or accesses properties of that class. In order to minimise coupling to the absolute necessary, you will want to keep the public interface of the class as small as possible. When you designate something as public, you're marking it "for general use". That public piece should then be rather stable and not change, or you risk breaking a lot of coupled code if you do change it.

    Marking something as protected or private marks these parts as not for general consumption; it clarifies that these implementation details might change in the future or are not supposed to be used by other code "not in the know". This allows you to easier refactor those parts later as necessary and having a better idea of what other parts might break as a result. It also helps to ensure the internal state of the class is consistent when external code won't directly modify internal values without completely understanding how it should do so.

    PHP will help you honour those markers in the general case by throwing errors when naïvely trying to access protected or private properties "from the outside"; that prevents most accidental usage and unwanted coupling. PHP is not going to bend over backwards to ensure those properties stay inaccessible under all possible circumstances. If you're really bent on shooting your own foot, so be it. Perhaps you need to do so for testing purposes; it would be counter productive to absolutely prevent you from doing so.

    In the mantra of Python:

    We're all consenting adults here.

提交回复
热议问题