Classes4 min readExamples run on PHP 8.5.10

PHP Classes: Constructors and Instance Methods

Group data and behavior in an object, initialize it with a constructor and access properties through $this.

Define an object

A class describes its objects’ properties and methods. Use new with the class name to create an instance. A constructor named __construct can initialize properties from the arguments supplied at creation.

Access instance data

Inside an instance method, $this refers to the current object. The arrow operator accesses its properties and methods. Each instance can therefore use the same method definition with different stored data.

A common mistake

A local variable and an object property are different locations. Assigning $name = $name does not store a constructor argument in a property; use $this->name = $name.

Tested examples

Minimal working example
<?php class Label { public function __construct(private string $name) {} public function text(): string { return $this->name; } } echo (new Label("Ada"))->text();
Output
Ada