Concept

How does PHP visibility protect class data?

ComputerScienceOne / Data Visibility

"Recall that encapsulation involves not only the grouping of data, but the protection of data. The class declaration above achieves the grouping of data. To provide for the protection of data, PHP defines several visibility keywords that specify what segments of code can “see” the variables. Visibility in this context determines whether or not a segment of code can access and/or modify the variable’s value. PHP defines three levels of visibility using they keywords public, protected and private. Each of these keywords can be applied to both member variables and member methods.\n\n• public – This is the least restrictive visibility level and makes the member variable visible to any code segment.\n\n• protected – This is a bit more restrictive and makes it so that the member variable is only visible to the code in the same class, or any subclass of the class. 1\n\n• private – this is the most restrictive visibility level, private member variables are only visible to instances of the class itself.\n\nTable 45.1 summarizes these four keywords with respect to their access levels. It is important to understand that protection is in the context of encapsulation and does not involve protection in the sense of “security.” Protection is this context is a design principle. Limiting the access of variables only affects how the rest of the code base interacts with our class and its data.\n\nModifier | Class | Subclass | World\n\npublic | Y | Y | Y\n\nprotected | Y | Y | N\n\nprivate | Y | N | N\n\nTable 45.1.: PHP Visibility Keywords & Access Levels\n\nIn general, it is best practice to make member variables private and control access to them via accessor and mutator methods (see below) unless there is a compelling design reason to increase their visibility.\n\n1 Subclasses are involved with inheritance, another object-oriented programming concept that we will not discuss here."

Related Ideas

How does PHP visibility protect class data? | ComputerScienceOne | Bifalgorithm | Bifalgorithm