PHP · Course navigation

PHP Classes

Hide a property and change it only through methods.

On this page
Before you start

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
<?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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1<?php
2class 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();
17echo $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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading