What are the advantages of using getters and setters instead of functions or simply public fields in PHP?

What are the advantages of using getters and setters instead of functions or simply public fields in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Encapsulation Gap: Why Getters and Setters Matter in PHP

In modern PHP development, the debate between exposing public properties versus encapsulating data behind private fields with accessor methods is a frequent discussion point. While using public fields might seem like the path of least resistance—offering direct access without boilerplate code—it often undermines the architectural integrity of an object-oriented system. The decision to use getters and setters isn't merely about following a specific style guide; it is about controlling how data enters and leaves your class, ensuring consistency, and maintaining the ability to evolve your codebase without breaking existing consumers.

When you declare fields as public, you are effectively handing over the keys to the kingdom of that object. Any external script or another class can read or modify $this->firstField directly. This creates a "fat client" scenario where the internal state of an object becomes fragile. If you later decide that firstField must be converted from a string to an integer upon assignment, every instance of your class currently in use will break unless you refactor every single place where that property is assigned. With public fields, the validation logic lives inside the class but can be bypassed entirely by external code.

Encapsulating data with private fields and explicit getter/setter methods enforces a strict contract on how an object interacts with the outside world. Consider a scenario where you need to normalize input before storing it. Using a setter allows you to intercept the value:

class User {
    private $email;

    public function setEmail(string $value) {
        // Validation and normalization happen here
        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->email = strtolower(trim($value));
        } else {
            throw new InvalidArgumentException('Invalid email format.');
        }
    }

    public function getEmail(): ?string {
        return $this->email;
    }
}

With this pattern, the internal representation of $email is guaranteed to be a lowercase string. Even if an external library or a legacy script attempts to assign a value directly to a public property (which isn't possible with private fields), the logic remains intact because the only valid entry point is through the setter. This is the essence of the Law of Demeter and general encapsulation principles: hide implementation details behind a stable interface.

There is also the matter of lazy initialization. A getter provides a natural hook to check if data has been loaded yet, perhaps fetching it from a database on first access, whereas a public field often implies the value exists immediately or defaults to null without any context. Furthermore, in frameworks like Laravel, which utilize dependency injection and service containers, immutable properties or specific types are sometimes preferred for caching strategies that rely on property reflection. While PHP's magic methods (__get, __set) can mimic this behavior, explicit methods are generally preferred for readability and type safety, especially when using typed properties and return types introduced in PHP 7.4+.

However, the trade-off is verbosity. For simple data transfer objects (DTOs) or entities that map directly to flat database rows without business logic, public properties can reduce line count. The advantage of getters/setters shines brightest when the object represents a complex domain model where state transitions need validation, logging, or triggering side effects during mutation.

Ultimately, the choice between public fields and encapsulated accessors comes down to how much you value future-proofing your code over immediate brevity. In enterprise applications and long-lived projects, the rigidity provided by private fields and explicit accessors prevents subtle bugs caused by inconsistent data states, making the system significantly more maintainable as requirements change.

Our network