Skip to content

Chapter 1 of 7

Object-Oriented Foundations

At the heart of modern PHP is its object-oriented programming model. A class is a blueprint that defines the properties (variables) and methods (functions) its objects will have. You create an instance of a class using the new keyword, which also triggers the class's constructor, a special method named __construct() designed to initialize the new object's state. Many modern PHP constructors use promoted parameters, allowing properties to be declared and assigned directly in the constructor signature for more concise code.

Controlling who can access a class's internals is essential for writing maintainable code. PHP provides three access modifiers: public members are accessible from anywhere, protected members are accessible within the class itself and any subclasses that inherit from it, and private members are restricted to the defining class alone. These modifiers let you hide implementation details behind a clean public interface, which is a core principle of encapsulation.

Beyond instance-level data, PHP lets you define static properties and methods that belong to the class as a whole rather than to any particular object. Static members are accessed through the class name, such as Counter::$count, and are useful for shared counters, configuration values, or utility helpers that do not depend on per-instance state. The self keyword inside a static method refers to the same class, providing a way to reference static properties without resorting to the fully qualified name.

All chapters
  1. 1Object-Oriented Foundations
  2. 2Inheritance, Interfaces, and Traits
  3. 3Namespaces and Dependency Management
  4. 4The PHP Type System
  5. 5Working with Arrays and Strings
  6. 6Databases, Sessions, and Error Handling
  7. 7Closures, Generators, and Magic Methods

Drill it

Reading is not remembering. These come from the Php Programming deck:

Q

What is a class in PHP OOP?

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will have.class User { public string $na...

Q

What is the difference between public, protected, and private visibility in PHP?

public – accessible from anywhere.protected – accessible within the class and its subclasses.private – accessible only within the defining class.These are known...

Q

How do you create an object from a class in PHP?

Use the new keyword:$user = new User();This calls the class constructor (__construct) if one is defined.

Q

What is the purpose of the __construct() magic method?

__construct() is the constructor that runs automatically when an object is created with new.public function __construct(public string $name) {}It initializes ob...