PHP: Getters and Setters.

This is a short introductory tutorial on how to use “Getters” and “Setters” in PHP. “Getters” and “Setters” are object methods that allow you to control access to a certain class variables / properties. Sometimes, these functions are referred to as “mutator methods”. A “getter” allows to you to retrieve or “get” a given property. A “setter” allows you to “set” the value of a given property.

Lets take a look at the following PHP class:

In our Person class above, we have two private properties called $name and $dateOfBirth. Because they are private properties, you will be unable to access them like so:

If you attempt to run the code above, you will end up with the following fatal error:

Fatal error: Cannot access private property Person::$name

To provide access to our private properties, we have created two “getters” called getName and getDateOfBirth. If you take a look at the Person class above, you’ll see that these functions simply return the values of our two private properties. That is all they do.

Because the visibility of these two properties is set to private, you will also be unable to modify or “set” their values. Instead, you will have to use one of the “setter” functions that we created: setName or setDateOfBirth.

Let’s take a look at a simple example of our getter and setter functions being used:

In the PHP code above, we:

  1. Instantiated our Person object.
  2. We “set” the $name property to “Wayne” using our setter method setName.
  3. We then retrieved the value of the $name property by using our getter function getName.

Pretty simple, eh?

Why use getters and setters? What is the point?

The getters and setters that we created in our Person class above are pretty pointless as they merely provide access to our private properties. Beyond that, they don’t do anything.

However, what if we wanted to add a layer of validation to prevent our object from being misused? For example, what if we wanted to make sure that the person’s $name variable is a string variable and not something else? Well, we can simply add that layer of validation to our setter method:

In the PHP code above, we modified the setter method setName so that it validates the $name variable. Now, if a programmer attempts to set the $name variable to an array or a boolean, our function will throw an Exception. If we wanted to, we could also make sure that the $name variable is not a blank string.

Hopefully, you found this tutorial to be helpful!