Skip to content
Learn Netverks

Lesson

Step 21/36 58% through track

classes-objects

Classes and objects

Last reviewed May 28, 2026 Content v20260528
Track mode
server_script
Means
Server runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Classes and objects: the syntax, APIs, and habits you need before advancing in PHP.

Frameworks like Laravel are OOP-first—classes, visibility, and inheritance show up in every code review.

You will apply Classes and objects in contexts like: LAMP/LEMP stacks, Laravel apps, WordPress themes/plugins, and shared hosting.

Write PHP in the editor and click Run on server—the dev runner executes your script and returns stdout/stderr (set LEARNING_RUNNER_ENABLED=true locally).

When you can explain the previous lesson's ideas without copying starter code.

Objects bundle data and behavior. PHP supports classes, interfaces, traits, enums (PHP 8.1+), and readonly properties (PHP 8.2+).

Basic class

class User {
    public function __construct(
        public string $name,
        public string $email,
    ) {}

    public function label(): string {
        return $this->name;
    }
}

$u = new User('Ada', 'ada@example.com');

Constructor property promotion

PHP 8 shorthand declares and assigns properties in the constructor parameter list—common in DTOs and value objects.

$this

Inside instance methods, $this refers to the current object. Static methods use self:: or static::.

Important interview questions and answers

  1. Q: Class vs object?
    A: Class is the blueprint; object is an instance created with new.
  2. Q: When use readonly properties?
    A: Immutable value objects initialized once in the constructor—PHP 8.2+.

Self-check

  1. What keyword creates an instance?
  2. What does constructor promotion save you from writing?

Tip: Constructor property promotion (PHP 8) keeps DTOs short—pair with readonly properties when values must not change.

Interview prep

Constructor promotion?

PHP 8 lets you declare constructor parameters with visibility modifiers—they become properties automatically, reducing boilerplate in DTOs.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • $this meaning?
  • Constructor promote?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump