Skip to content

Chapter 17 of 38

Classes and Objects

Model properties, methods, visibility, static state, readonly data, and invariants.

40 minutes 10 quick checksBy Subha Prasad
Lesson 17 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Classes group state and behavior. Keep properties private or readonly where possible and expose operations that preserve valid state.

Practical example

<?php
final class Percentage {
  public function __construct(public readonly float $value) {
    if ($value < 0 || $value > 100) throw new InvalidArgumentException('0..100 required');
  }
  public function asRatio(): float { return $this->value / 100; }
}

$this is the receiver. Static mutable state hides dependencies and complicates long-running workers. Magic methods should remain unsurprising. Prefer small cohesive objects, explicit collaborators, and value objects for stable domain concepts.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes class?
Which PHP term matches this description: A type declaring properties, methods, and invariants.
Which statement best describes object?
Which PHP term matches this description: A runtime instance of a class.
Which statement best describes visibility?
Which PHP term matches this description: Public, protected, or private member access control.
Which statement best describes static member?
Which PHP term matches this description: A member belonging to the class rather than an instance.
Which statement best describes readonly property?
Which PHP term matches this description: A typed property restricted from reassignment after initialization.

0 of 10 checks passed

Your progress is saved on this device.

Classes and Objects | PHP Lesson | Subha Prasad