PracticeAccess modifiers: public vs. private

Practice: Public vs. Private access modifiers

In the "Public vs. private access modifiers" tutorial, we learned how and when to use the public and private access modifiers. While public code can be approached from outside the class, private code can be accessed only from within the class.

In the following section, we will be able to practice everything that we learned about the use of the public and private access modifiers by writing our own code.

Let's practice what we have just learned

* Press on the "solution button" to see our suggested solution.

We use the private access modifier in order to:

  • A Limit the access to a class.
  • B Limit the access to properties.
  • C Limit the access to methods.
  • D B+C
Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Coding exercise

Let's return to the User class that we developed in the previous tutorials, but let’s now define the $firstName of the user as a private property.

This is the User class:

class User {
  // your code goes here
}

Create a new class property with the name of $firstName, and prevent any code from outside the class from changing the property value by using the appropriate access modifier (private or public).

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Create a method to set the $firstName property value.
Use the right access modifier for the method (public/private).

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Now, create a method to return the $firstName value.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Create a new user object with the name of $user1, set its name to "Joe" and make it return its name.

Expected result:
Joe

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code
comments powered by Disqus