Getters and Setters
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 40 of 91.
Now that you understand access modifiers, how do you safely interact with private properties from outside the class? The answer is getters and setters - public methods that provide controlled access to private data.
A getter retrieves a property's value, while a setter modifies it. This pattern lets you add validation or logic when data is accessed or changed:
<?php
class User {
private string $email;
private int $age;
public function getEmail(): string {
return $this->email;
}
public function setEmail(string $email): void {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
}
}
public function getAge(): int {
return $this->age;
}
public function setAge(int $age): void {
if ($age >= 0 && $age <= 150) {
$this->age = $age;
}
}
}
$user = new User();
$user->setEmail("john@example.com");
$user->setAge(25);
echo $user->getEmail() . "\n";
echo $user->getAge();
Output:
john@example.com
25The setter validates the email format and ensures age is reasonable before storing the values. Without setters, anyone could assign invalid data directly. You can also create read-only properties by providing only a getter, or write-only properties with only a setter.
Key Point: Getters and setters give you control over how private data is accessed and modified, allowing validation, formatting, or any custom logic.
Challenge
EasyLet's build a product inventory system that uses getters and setters to protect and validate product data. You'll create a Product class that ensures prices are always positive and stock quantities are never negative — demonstrating how setters can enforce business rules.
You'll organize your code across two files:
Product.php— Create aProductclass with three private properties:$name(string),$price(float), and$stock(integer). Implement getters and setters for each property with the following validation rules:setName()should only accept non-empty strings — if the string is empty after trimming, don't update the propertysetPrice()should only accept values greater than 0 — reject zero or negative pricessetStock()should only accept values of 0 or greater — reject negative stock quantities
getInfo()that returns"[name]: $[price] ([stock] in stock)"with the price formatted to 2 decimal places.main.php— Include the Product file. You'll receive four inputs: a product name, a price, a stock quantity, and a new price to update. Create aProductinstance and use the setters to assign the initial name, price (converted to float), and stock (converted to integer). Print the result ofgetInfo(). Then attempt to update the price with the new price value (converted to float) and printgetInfo()again. Finally, attempt to set the stock to-5(an invalid value) and printgetInfo()one more time to confirm the stock wasn't changed.
Your setters act as gatekeepers — they validate incoming data before allowing changes to the private properties. When invalid data is passed (like a negative stock), the setter simply ignores it, keeping the existing valid value intact. This is the power of encapsulation: your object maintains its integrity regardless of what external code tries to do.
Cheat sheet
Use getters and setters to provide controlled access to private properties. A getter retrieves a value, while a setter modifies it with optional validation:
<?php
class User {
private string $email;
private int $age;
public function getEmail(): string {
return $this->email;
}
public function setEmail(string $email): void {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
}
}
public function getAge(): int {
return $this->age;
}
public function setAge(int $age): void {
if ($age >= 0 && $age <= 150) {
$this->age = $age;
}
}
}
$user = new User();
$user->setEmail("john@example.com");
$user->setAge(25);
echo $user->getEmail(); // john@example.com
echo $user->getAge(); // 25
Setters can validate data before storing it. If validation fails, the setter can ignore the update, keeping the existing value intact. You can create read-only properties by providing only a getter, or write-only properties with only a setter.
Try it yourself
<?php
require_once 'Product.php';
// Read inputs
$name = trim(fgets(STDIN));
$price = trim(fgets(STDIN));
$stock = trim(fgets(STDIN));
$newPrice = trim(fgets(STDIN));
// TODO: Create a new Product instance
// TODO: Use setters to assign initial name, price (as float), and stock (as integer)
// TODO: Print the result of getInfo()
// TODO: Update the price with newPrice (as float) and print getInfo() again
// TODO: Attempt to set stock to -5 (invalid) and print getInfo() to confirm stock wasn't changed
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern