OOP in PHP

Contents
Introduction
Class and object
Constructor
public, protected, private
Static members

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.

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.

Article author: Arthur Isaev

Related articles
Development with PHP
OOP in PHP
PHP 8 Classes
Inheritance in PHP
Methods from two sibling classes: traits

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: