PHP Classes
Hide a property and change it only through methods.
On this page
PHP functions.
- Hide a property and change it only through methods.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
<?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";2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
<?phpclass 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";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 |
Behind the scenes
How PHP processes this code
The PHP runtime executes the script. echo writes to the response or terminal output.
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.