OOP in PHP

Содержание
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

Похожие статьи
Development with PHP
OOP in PHP
PHP 8 Classes
Inheritance in PHP
Methods from two sibling classes: traits

Поиск по сайту

Подпишитесь на Telegram канал @aofeed чтобы следить за выходом новых статей и обновлением старых

Перейти на канал

@aofeed

Задать вопрос в Телеграм-группе

@aofeedchat

Контакты и сотрудничество:
Рекомендую наш хостинг beget.ru
Пишите на info@urn.su если Вы:
1. Хотите написать статью для нашего сайта или перевести статью на свой родной язык.
2. Хотите разместить на сайте рекламу, подходящую по тематике.
3. Реклама на моём сайте имеет максимальный уровень цензуры. Если Вы увидели рекламный блок недопустимый для просмотра детьми школьного возраста, вызывающий шок или вводящий в заблуждение - пожалуйста свяжитесь с нами по электронной почте
4. Нашли на сайте ошибку, неточности, баг и т.д. ... .......
5. Статьи можно расшарить в соцсетях, нажав на иконку сети: