Home >PHP >Object-oriented PHP

Object-oriented PHP

Object-oriented programming in PHP from the basics: classes and objects, inheritance, interfaces, static members and traits, exceptions, namespaces, autoloading of classes and Composer. The examples run in PHP 7.4 and 8, and where PHP 8 makes the code shorter, they refer to the Migrating to PHP 8 series.

A class joins data and the functions that work with it into a single unit. How to write your first class, create objects from it, protect data from unwanted changes and what to watch out for when copying objects.

read more →

A child class takes over the properties and methods of its parent and can extend or change them. How to inherit, call methods of the parent, what abstract classes are for, when to forbid inheritance with final and when it is better not to use inheritance at all.

read more →

An interface describes what a class must be able to do, but not how. Code that relies on an interface then works with any class that fulfils it – for example with real sending of e-mails on the website and with a fake one in a test.

read more →

Not everything belongs to a particular object. Constants and static methods belong to the whole class, traits share code between classes without inheritance. How to use them and where caution pays off.

read more →

An exception interrupts the code and hands the error over to whoever can deal with it. How to throw and catch exceptions, why catch(Exception) does not catch everything, how to write a custom exception and what to do with an exception that nobody caught.

read more →

Namespaces separate the classes of different parts of a website and of libraries, so that their names do not clash. How to write them, how to use classes from another namespace with use and which trap almost everyone who starts with them runs into.

read more →

Instead of dozens of require lines, it is enough to tell PHP where to look for classes. How to write a function for autoloading classes according to the PSR-4 conventions, how to arrange the folders and why a website that works on Windows can stop working on the server.

read more →

Composer downloads the libraries a website needs, keeps an eye on their versions and generates an autoloader for your own classes too. How to use it, what belongs in composer.json and composer.lock and how to deploy a website with libraries to hosting without SSH.

read more →