Getters in PHP

A getter method is responsible for retrieving the value of a private or protected property within a class. It allows external code to access the property’s value without directly manipulating it. Getters typically have names prefixed with “get.”

Example: Here, the getName method is a getter that returns the value of the private $name property.

PHP




<?php
 
class Person
{
    private $name;
 
    public function __construct($name)
    {
        $this->name = $name;
    }
 
    public function getName()
    {
        return $this->name;
    }
}
 
// Usage of the getter
$person = new Person("John Doe");
 
echo $person->getName();
 
?>


Output

John Doe

In this example, .

What are getters and setters methods in PHP ?

In object-oriented programming, getters and setters are methods used to access and modify the private or protected properties of a class. These methods provide a controlled way to retrieve and update the values of class properties, promoting encapsulation and maintaining the integrity of an object’s state.

Similar Reads

Getters in PHP

A getter method is responsible for retrieving the value of a private or protected property within a class. It allows external code to access the property’s value without directly manipulating it. Getters typically have names prefixed with “get.”...

Setters in PHP

...

Benefits of using the Getters and Setters

A setter method is used to modify the value of a private or protected property within a class. It allows controlled access to the internal state of an object by providing a way to update its properties. Setters typically have names prefixed with “set.”...

Differences between Getters and Setters

...

Conclusion

Encapsulation: Getters and setters encapsulate the internal state of an object, hiding its implementation details and providing controlled access. Validation: Setters can include validation logic to ensure that the new value meets certain criteria before updating the property. Flexibility: Getters and setters allow developers to modify the internal representation of a property without affecting external code that uses the class....