PHP Classes
Hide a property and change it only through methods.
PHP
<?php
class Counter {
private int $value = 0;
public function increment(): void {
$this->value++;
}
public function value(): int {
return $this->value;
}
}
$counter = new Counter();
$counter->increment();
$counter->increment();
echo $counter->value(), "\n";Output
2
Explanation
A PHP class declares properties and methods. private means only code inside the class can touch the property, and $this refers to the current object. Inside methods, members are reached with the -> operator.
new Counter() creates an object with value 0. Each call to increment adds one, and the value() method is the only way outside code can read it.
Explore the dry run
Guided walkthroughReady
1
<?php2
class Counter {3
private int $value = 0;4
5
public function increment(): void {6
$this->value++;7
}8
9
public function value(): int {10
return $this->value;11
}12
}13
14
$counter = new Counter();15
$counter->increment();16
$counter->increment();17
echo $counter->value(), "\n";Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| A hidden property that starts at zero. | — | — | |
| Create the object. | value = 0 | — | |
| The first call raises value to 1. | value = 1 | — | |
| After two calls the value is 2. | value = 2 | 2 |
Cost and common mistakes
O(1) per method call.
- Reading $counter->value directly is a fatal error because the property is private.
- Forgetting $this-> inside a method refers to a local variable, not the property.
Try it yourself
Add a decrement method.
Reveal answer and reasoning
public function decrement(): void { $this->value--; } lowers the value by one.