Why Do We Need Access Modifiers?
Learn why to using access modifiers in code.
We'll cover the following
We need access modifiers to limit the modifications that code from outside the classes can make to the class’s methods and properties.
Once we define a property or method as private, only methods within the class are allowed to approach it. So, in order to interact with private methods and properties, we need to provide public methods. Inside these methods, we can put logic that can validate and restrict data that comes from outside the class.
Example: Validating checks using access modifiers
In our example, we can validate that only specific car models can make their way and be assigned to the $model
property by defining the allowed alternatives for models in the setModel()
method.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy