Sobes.tech
Junior — Middle

Is it correct to use the getter method to access private properties of a class?

sobes.tech AI

Answer from AI

Using getter methods to access private properties of a class in PHP is a correct and recommended practice. Private properties are not accessible directly from outside the class, so getters provide controlled access to these data, allowing for additional logic when reading the value if necessary.

Example:

class User {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function getName(): string {
        return $this->name;
    }
}

$user = new User("Ivan");
echo $user->getName(); // Outputs: Ivan

Thus, getters help encapsulate data and maintain control over their access.

Is it correct to use the getter method to access… - sobes.tech