This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
While the public access modifier allows a code from outside OR inside the class to access the class’s methods and properties, the private modifier prevents access to a class’s methods or properties from any code that is outside the class. In this video we’ll talk about why that can be useful.
More Advanced Title Case
Improved Title Case Function for PHP
Case Converter Bundle on Packagist
Access Modifiers
Access modifiers allows us to control the access, or visibility, of our properties. These access modifiers are public, private, or protected. If declared using var, the property will be defined as public. When declaring a property, the visibility MUST be defined by an access modifier.
Public | Publicly accessible from anywhere, even from outside the scope of the class. |
---|---|
Private | Accessed within the class itself. It protects properties and methods from being access from outside the class. |
Protected | Same as private, except by allowing child (sub) classes to access protected parent (super) properties and methods. |
Don't Allow Property Change
If we wanted to keep someone from changing a property after it’s been set the first time, we could use two different options. Both require that the property itself is set to private. Only allow the property to be set in the __construct method and don't set up another method to change the property. Add a conditional to any method that modifies the property to first check that the property is empty before adding a value.
Using Private Methods
Methods use access modifiers as well. So we can also use private to define a method. We may want to setup a method for formatting a property, but we only want to call that method from the __construct method or another method that combines more logic. For example, we only want to allow updating the user's name if we also verify the user's email.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up