PHP
Getter and setter methods
Provide controlled access to private properties with getter and setter methods.
What are getters and setters?
Getters and setters are methods that provide controlled access to private properties. A getter reads; a setter writes.
A common PHP pattern: declare private int $price;, read it with getPrice(): int, and write it with setPrice(int $price): void. Inside the setter you can validate, for example reject negative prices.
Besides blocking direct access, this pattern lets you run extra logic (logging, computation) when a value changes. Some frameworks also use magic __get and __set methods; we'll cover those in another lesson.
Getter example and read-only properties
A getter is a public method that returns the value of a private property. Its name is usually get + property name: getName, getPrice, getBalance.
Example: class Product { private int $price; public function getPrice(): int { return $this->price; } }. Here outside code cannot write $product->price, but it can read via $product->getPrice().
Getters also create read-only properties: if you skip setPrice, the price is set only inside the class (for example via the constructor) and cannot be changed later.
Exercise Product class with a validating setter
Define a Product class with a private int $price = 0 property. Add public function setPrice(int $price): void that rejects negatives with if ($price < 0) { return; } and then runs $this->price = $price. Add public function getPrice(): int that does return $this->price. Then create $product = new Product(), first call $product->setPrice(-50) (rejected), then $product->setPrice(200) and print echo $product->getPrice() . "\n".
Show example solution
Declare private $price, in setPrice add if ($price < 0) return; then $this->price = $price. getPrice returns $this->price.
Example solution:
<?php
// Define a Product class with a validating setter
class Product {
private int $price = 0;
public function setPrice(int $price): void {
if ($price < 0) {
return;
}
$this->price = $price;
}
public function getPrice(): int {
return $this->price;
}
}
$product = new Product();
$product->setPrice(-50);
$product->setPrice(200);
echo $product->getPrice() . "\n";
Test yourself
-
Match the getter and setter expressions
- getName()
- Reads the property
- setName($val)
- Writes the property
- Validation
- Happens in setter
- return $this->name
- Getter body
-
Complete the getter body
public function getPrice(): int {
return ____;
}
Show answer
public function getPrice(): int {
return $this->price;
}
-
What is the main purpose of a setter method?
- To delete the property
- To ignore the property
- To assign random values
- To validate while assigning a value
Show answer
To validate while assigning a value — Correct. A setter provides controlled, validated assignment to a private property.
Next lesson: Summary - Visibility