Object-Oriented PHP

PHP Classes and Objects: A Practical Introduction

Understand how to define PHP classes, create objects, use properties and methods, and control access to class members.

PHP Classes and Objects: A Practical Introduction

Object-oriented programming organizes code around objects that combine data and behavior. In PHP, a class defines the structure and behavior of objects created from it.

Define a Class

A class can contain properties and methods. The $this keyword refers to the current object.

class Product
{
    public function __construct(
        public string $name,
        private float $price
    ) {}

    public function getPrice(): float
    {
        return $this->price;
    }
}

$product = new Product("Keyboard", 49.90);
echo $product->name;
echo $product->getPrice();

This example uses constructor property promotion, available in modern PHP versions. The private property can only be accessed from within the class.

Visibility

PHP supports public, protected, and private visibility. Public members can be accessed from outside the class. Protected members are available in the class and its subclasses. Private members are limited to the class that declares them.

Use the narrowest visibility that meets the design requirements.

Constructors and Methods

The __construct() method runs when an object is created. Methods define behavior and can accept parameters and return values like regular functions.

Avoid putting unrelated responsibilities into one class. Small, focused classes are generally easier to test and maintain.

Static Members

Static properties and methods belong to the class rather than an individual object. They are accessed using the :: operator. Use static members when behavior genuinely belongs to the class as a whole, not as a shortcut for global state.

Conclusion

Classes and objects help structure larger PHP applications. Start with clear responsibilities, controlled visibility, and small methods; then explore interfaces, inheritance, and dependency injection as your designs grow.

Share this page Help other developers discover this resource.