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

前端 未结 2 1496
耶瑟儿~
耶瑟儿~ 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:12

    Great question! I would like to add few more points

    The purpose of specifying visibility in OOP languages is:

    1. To show what the properties and methods are meant to do. This is to bring clarity among developers as to how to access/modify the property and methods, to decide whether to extend the class or not.
    2. The properties that are set inside its respective class is validated and set to correct values and it is safe to be used inside the Class without checking the property type.
    3. It is not a foolproof way to secure the data from modification.

    The Purpose of Closures is to throw a piece of function into a variable or another function to perform some activity once in a while. Instead of dedicating a separate section code in global scope for performing an action once in a while and not look at it later you can use closures.

    Reflections are meant to introspect objects to know its properties, methods, class etc. It is useful to identify dependencies. Larvel uses reflection to perform dependency injection of objects.

    Yes as you said you can use Closures and Reflection to work around visibility but it should be viewed as a language feature rather than a design flaw as no language can secure data 100%

提交回复
热议问题