PHP
Summary - Visibility
Build a temperature class with public, private, getter and setter.
Summary - Visibility
In this group you learned three visibility modes:
public: accessible everywhere.protected: class and subclasses.private: only the declaring class.
For encapsulation, make internal state private and expose controlled access with getters and setters. Validation in setters protects invariants. Now you'll combine all of this in a Temperature class.
Exercise Temperature class: encapsulation combined
Define a Temperature class with a private float $celsius = 0 property. Add public function setCelsius(float $value): void that rejects below absolute zero with if ($value < -273) { return; } and then runs $this->celsius = $value. Add public function getCelsius(): float that does return $this->celsius. Then create $temp = new Temperature(), call $temp->setCelsius(-500) (rejected), then $temp->setCelsius(25), and print echo $temp->getCelsius() . "\n".
Show example solution
Declare private float $celsius. In setCelsius add if ($value < -273) return; then $this->celsius = $value. getCelsius returns $this->celsius.
Example solution:
<?php
// Define a Temperature class
class Temperature {
private float $celsius = 0;
public function setCelsius(float $value): void {
if ($value < -273) {
return;
}
$this->celsius = $value;
}
public function getCelsius(): float {
return $this->celsius;
}
}
$temp = new Temperature();
$temp->setCelsius(-500);
$temp->setCelsius(25);
echo $temp->getCelsius() . "\n";
Tips for choosing visibility
Remember: public for broad access, protected for inheritance hierarchy, private for class-only. Which to choose depends on who needs to see the data.
Internal state starts private; open to protected only when needed. Expose behavior, not data. This makes code easier to change: you can alter the internal representation without breaking outside callers.
In the next group we'll look at static members for class-level data.
Test yourself
-
Match all visibility modes
- public
- Accessible everywhere
- protected
- Class and subclasses
- private
- Class only
- Setter + Getter
- Controlled access
-
Which visibility fits a bank account balance?
- public - changeable everywhere
- private - class only, with a setter
- protected - subclasses can change it
- No visibility needed
Show answer
private - class only, with a setter — Correct. Balance should be private and change only via deposit/withdraw methods.
Next lesson: static property