OOP in PHP

Introduction

Object-oriented programming in PHP groups data (properties) and the functions that work on it (methods) into classes; a object is one live instance of a class. Russian version: classes in PHP 8.

Author: Arthur Isaev

Class and object

<?php namespace Aredel\Demo; class Article { public string $title = ''; public function headline(): string { return '<h1>' . $this->title . '</h1>'; } } $a = new Article(); $a->title = 'Hello'; echo $a->headline();

$this inside a method means the current object. -> accesses its members. No type for the property would also work, but typed properties (PHP 7.4+) catch mistakes early.

Constructor

__construct() runs once at new time — the place for mandatory setup, so an object can never exist half-initialized:

<?php namespace Aredel\Demo; class Counter { public function __construct(private int $start = 0) { } public function next(): int { return ++$this->start; } }

Constructor property promotion (the private int in the signature, PHP 8.0+) declares and assigns the property in one line.

public, protected, private

public — callable from anywhere. protected — this class plus children (the extension point for inheritance). private — this class only. Default to the strictest level that works: public API small, internals private, seam for children protected.

Static members

static members belong to the class, not to any object — no $this inside, called as Counter::reset(). Good for factories and pure helpers; bad as hidden global state, because static state persists for the whole request and resists testing.

Автор статьи: Андрей Олегович