PHP Getters and Setters

Safeguarding and Sculpting with Getters and Setters

In the last article, we covered visibility modifiers and set all of our properties to private.

If we wanted to access those properties or modify them in their current state, we wouldn’t be able to. That’s where getters and setters, or accessors and mutators, come into play.

Getters and setters are just the public methods that either modify or retrieve a property. With the various setter methods, we can use checks to validate the submitted data. For example, let’s say that we were modifying the $year property with our setter. The argument that’s received by the setter method would be validated for, i.e. negative numbers, since you can’t have a negative year.

Getters

With getters, we can either return the exact property value or some variation of it. In our Car class, we have a property called $car_on that stores a boolean value of either or 1. We don’t have to return 0 or 1, but can instead return a string such as off or on.

Let’s jump into some examples since getters and setters are relatively easy to comprehend. We’ve actually already seen a getter in action. In our GermanShepherd class we used the get_eye_color() method to return the eye color. It already followed the naming convention of a getter, which was get followed by the property that you’re trying to return.

<?php
// Getters and Setters

class GermanShepherd
{
private $eye_color;
// ...

public function getEyeColor(): string
{
return $this->eye_color;
    }

// ...
}
Our does_shed() method is technically a getter as well. We just need to modify the name to contain the get string in front of it for naming convention. It’s a perfect example of returning a string even though the $does_shed property stores a boolean value.
<?php

class GermanShepherd {
  
    private $does_shed = true;
  
    //...
    public function getDoesShed(): string
    {
        return ($this->does_shed) ? "Yes" : "No";
    }
    //...
}

Setters

Setters follow a similar naming convention with two exceptions. You guessed the first one: the string set is prepended and not get. The other difference is that you will pass an argument to the setter each time. If we wanted to set the eye color, we would use the setEyeColor(string $eye_color) method. Setters do not return anything, so our return type will be set to void.

<?php

class GermanShepherd {
  
    private $eye_color;
  
    //...
    public function setEyeColor(string $eye_color): void
    {
        $this->eye_color = $eye_color;
    }
    //...
}
Let’s run through and generate getters and setters for the remainder of the properties. If you’re using an editor like PHPStorm, you can have the getters and setters auto-generated for you. In PHPStorm, click Code -> Generate -> Getters and Setters. This will generate all of your getters and setters.

One thing to note if you’re using this PHPStorm feature is the way that boolean getters are defined. Since we’re asking if the value is true or not, the getter is named with the is string prepended, such as isDoesShed(). You can rename it to getDoesShed(), especially if you’re actually going to return a string, but I’ll leave it as is. If you don’t want certain getters and setters to be present, you can unselect them and they will not be accessible nor modifiable.
<?php

class GermanShepherd
{
    //...

    private $eye_color;
    private $dob;
    private $does_shed = true;
    private $kingdom = "Animalia";
    private $phylum = "Chordata";
    private $class = "Mammalia";
    private $order = "Carnivara";
    private $family = "Canidae";
    private $genus = "Canis";
    private $species = "Canis Lupus";
    private $subspecies = "Canis Lupus Familiaris";
    private $breed = "German Shepherd Dog";
    private $fur_color;

    //...

    /**
     * @return string
     */
    public function getEyeColor(): string
    {
        return $this->eye_color;
    }

    /**
     * @param string $eye_color
     */
    public function setEyeColor(string $eye_color): void
    {
        $this->eye_color = $eye_color;
    }

    /**
     * @return string
     */
    public function getDob(): string
    {
        return $this->dob;
    }

    /**
     * @param string $dob
     */
    public function setDob(string $dob): void
    {
        $this->dob = $dob;
    }

    /**
     * @return bool
     */
    public function isDoesShed(): bool
    {
        return $this->does_shed;
    }

    /**
     * @param bool $does_shed
     */
    public function setDoesShed(bool $does_shed): void
    {
        $this->does_shed = $does_shed;
    }

    /**
     * @return string
     */
    public function getFurColor(): string
    {
        return $this->fur_color;
    }

    /**
     * @param string $fur_color
     */
    public function setFurColor(string $fur_color): void
    {
        $this->fur_color = $fur_color;
    }

    //...
}
Since these are now all public methods, you can call them and access the property values after the object has been instantiated. We can also modify the property if a setter is in defined for that property.
<?php

$gs_dog = new GermanShepherd("Brown", "Jan 20, 2018", "Brown");
echo $gs_dog->getEyeColor();
$gs_dog->setEyeColor("Blue");
echo $gs_dog->getEyeColor();

In the example above, we use the constructor to create a new GermanShepherd with Brown eyes. We call our getEyeColor() method and it returns Brown. We then use our setter method to set the eye color to Blue. We call the getEyeColor() method again and this time it returns Blue.

You might have noticed a theme by now: each one of these articles build off of each other. So that we’re prepared for the next article, let’s implement the getters and setters for our Car class as well. And since we talked about it already, lets make a check inside of our setYear() method. If the year is less than zero, then we’ll echo a string that says “Not a valid year.” It will return void and prevent the property from being updated. Otherwise, it will allow the property to be updated. You can implement as many checks as you’d like.

<?php

// Car Class
class Car
{
    //...

    private string $color;
    private string $make;
    private string $model;
    private int $year;
    private int $fuel_type;
    private int $hp;
    private int $tq;
    private string $transmission;
    private string $vehicle_type;
    private float $exterior_height;
    private float $exterior_width;
    private float $exterior_length;
    private string $exterior_um;
    private float $weight;
    private string $weight_um;
    private bool $car_on;

    //...

    /**
     * @return string
     */
    public function getColor(): string
    {
        return $this->color;
    }

    /**
     * @param string $color
     */
    public function setColor(string $color): void
    {
        $this->color = $color;
    }

    /**
     * @return string
     */
    public function getMake(): string
    {
        return $this->make;
    }

    /**
     * @param string $make
     */
    public function setMake(string $make): void
    {
        $this->make = $make;
    }

    /**
     * @return string
     */
    public function getModel(): string
    {
        return $this->model;
    }

    /**
     * @param string $model
     */
    public function setModel(string $model): void
    {
        $this->model = $model;
    }

    /**
     * @return int
     */
    public function getYear(): int
    {
        return $this->year;
    }

    /**
     * @param int $year
     */
    public function setYear(int $year): void
    {
        if ( $year < 0 ) {
            echo "Not a valid year";
            return;
        }

        $this->year = $year;
    }

    /**
     * @return int
     */
    public function getFuelType(): int
    {
        return $this->fuel_type;
    }

    /**
     * @param int $fuel_type
     */
    public function setFuelType(int $fuel_type): void
    {
        $this->fuel_type = $fuel_type;
    }

    /**
     * @return int
     */
    public function getHp(): int
    {
        return $this->hp;
    }

    /**
     * @param int $hp
     */
    public function setHp(int $hp): void
    {
        $this->hp = $hp;
    }

    /**
     * @return int
     */
    public function getTq(): int
    {
        return $this->tq;
    }

    /**
     * @param int $tq
     */
    public function setTq(int $tq): void
    {
        $this->tq = $tq;
    }

    /**
     * @return string
     */
    public function getTransmission(): string
    {
        return $this->transmission;
    }

    /**
     * @param string $transmission
     */
    public function setTransmission(string $transmission): void
    {
        $this->transmission = $transmission;
    }

    /**
     * @return string
     */
    public function getVehicleType(): string
    {
        return $this->vehicle_type;
    }

    /**
     * @param string $vehicle_type
     */
    public function setVehicleType(string $vehicle_type): void
    {
        $this->vehicle_type = $vehicle_type;
    }

    /**
     * @return float
     */
    public function getExteriorHeight(): float
    {
        return $this->exterior_height;
    }

    /**
     * @param float $exterior_height
     */
    public function setExteriorHeight(float $exterior_height): void
    {
        $this->exterior_height = $exterior_height;
    }

    /**
     * @return float
     */
    public function getExteriorWidth(): float
    {
        return $this->exterior_width;
    }

    /**
     * @param float $exterior_width
     */
    public function setExteriorWidth(float $exterior_width): void
    {
        $this->exterior_width = $exterior_width;
    }

    /**
     * @return float
     */
    public function getExteriorLength(): float
    {
        return $this->exterior_length;
    }

    /**
     * @param float $exterior_length
     */
    public function setExteriorLength(float $exterior_length): void
    {
        $this->exterior_length = $exterior_length;
    }

    /**
     * @return string
     */
    public function getExteriorUm(): string
    {
        return $this->exterior_um;
    }

    /**
     * @param string $exterior_um
     */
    public function setExteriorUm(string $exterior_um): void
    {
        $this->exterior_um = $exterior_um;
    }

    /**
     * @return float
     */
    public function getWeight(): float
    {
        return $this->weight;
    }

    /**
     * @param float $weight
     */
    public function setWeight(float $weight): void
    {
        $this->weight = $weight;
    }

    /**
     * @return string
     */
    public function getWeightUm(): string
    {
        return $this->weight_um;
    }

    /**
     * @param string $weight_um
     */
    public function setWeightUm(string $weight_um): void
    {
        $this->weight_um = $weight_um;
    }

    /**
     * @return bool
     */
    public function isCarOn(): bool
    {
        return $this->car_on;
    }

    /**
     * @param bool $car_on
     */
    public function setCarOn(bool $car_on): void
    {
        $this->car_on = $car_on;
    }

    //...
}
Now that we have our getters and setters defined, we can create a Car object, make a few modifications to it with the setter properties, and then retrieve the properties with our getters. Just a side note: sometimes it doesn’t make sense to have setters…just ask hardcore object oriented developers. For example, if you create a Dog class with the kingdom Animalia, you shouldn’t change it. If you did, that would be weird.
<?php

$chevy = new Car(1997, "Chevy", "Camaro");
$chevy->setHp(900);
$chevy->setTq(1000);

echo $chevy->getHp();
echo $chevy->getTq();

$chevy->setYear(-1);

In the example above, we create a new vehicle and set the horsepower and torque properties with the help of the setter methods. We then retrieve the HP and Torque. Finally, we attempt to set the year with a negative number, but it just echos out a string stating that this is not a valid year.

That’s it. You’ve mastered getters and setters, or accessors and mutators, depending on who you ask; they mean the same thing.

Continue your learning with these articles

PHP Visibility Modifiers

NAVIGATING LOGIC’S SHADOWS WITH VISIBILITY KEYS

PHP – P51: VISIBILITY MODIFIERS

All about visibility modifiers. We tackled public, private, and protected visibility modifiers previously, but we get to understand what they are now.

PHP Getters and Setters

Safeguarding and Sculpting with Getters and Setters

PHP – P52: Getters and setters

If we wanted to access those properties or modify them in their current state, we wouldn’t be able to. That’s where getters and setters, or accessors and mutators, come into play.

Class Inheritance

PASSING DOWN CODE WISDOM THROUGH GENERATIONS

PHP – P53: CLASS INHERITANCE

Who would have guessed that PHP supports inheritance? Everyone using PHP since Object Oriented Programming became a thing, that’s who.

Leave a Reply