PHP Classes and Objects: Mastering Object-Oriented Programming

Explore the fundamentals of classes and objects in PHP, the building blocks of object-oriented programming. Learn how to define, instantiate, and utilize classes and objects to create robust and maintainable PHP applications.

2.1 Classes and Objects in PHP

In the realm of PHP development, understanding classes and objects is fundamental to mastering object-oriented programming (OOP). This section will guide you through the essential concepts of classes and objects, their relationship, and how they form the backbone of modern PHP applications.

Understanding Classes as Blueprints for Objects

In PHP, a class is a blueprint for creating objects. It defines a set of properties and methods that the objects created from the class will have. Think of a class as a template or a prototype that outlines the structure and behavior of the objects.

Defining a Class

To define a class in PHP, use the class keyword followed by the class name. Inside the class, you can define properties (variables) and methods (functions) that belong to the class.

 1<?php
 2
 3class Car {
 4    // Properties
 5    public $make;
 6    public $model;
 7    public $year;
 8
 9    // Constructor
10    public function __construct($make, $model, $year) {
11        $this->make = $make;
12        $this->model = $model;
13        $this->year = $year;
14    }
15
16    // Method
17    public function displayInfo() {
18        return "Car: $this->make $this->model, Year: $this->year";
19    }
20}
21
22?>

In this example, the Car class has three properties: $make, $model, and $year. It also includes a constructor method __construct() to initialize these properties and a method displayInfo() to return a string containing the car’s information.

Instantiating Objects in PHP

An object is an instance of a class. Once a class is defined, you can create objects from it. Each object can have its own values for the properties defined in the class.

Creating an Object

To create an object, use the new keyword followed by the class name.

1<?php
2
3// Creating an object of the Car class
4$myCar = new Car("Toyota", "Corolla", 2020);
5
6// Accessing object properties and methods
7echo $myCar->displayInfo(); // Outputs: Car: Toyota Corolla, Year: 2020
8
9?>

Here, $myCar is an object of the Car class. We pass the make, model, and year to the constructor to initialize the object. We then call the displayInfo() method to display the car’s information.

The Relationship Between Classes and Objects

Classes and objects are closely related. A class serves as a blueprint, while objects are specific instances of that blueprint. Each object can have different values for its properties, but they share the same structure and behavior defined by the class.

Object-Oriented Principles

  1. Encapsulation: Classes encapsulate data and behavior, providing a clear interface for interacting with objects.
  2. Abstraction: Classes abstract complex functionality, allowing developers to work with higher-level concepts.
  3. Inheritance: Classes can inherit properties and methods from other classes, promoting code reuse.
  4. Polymorphism: Objects can take on many forms, allowing for flexible and dynamic code.

Code Examples

Let’s explore more examples to solidify our understanding of classes and objects in PHP.

Example: Defining and Using a Class

 1<?php
 2
 3class Book {
 4    public $title;
 5    public $author;
 6    public $price;
 7
 8    public function __construct($title, $author, $price) {
 9        $this->title = $title;
10        $this->author = $author;
11        $this->price = $price;
12    }
13
14    public function getDetails() {
15        return "Title: $this->title, Author: $this->author, Price: $$this->price";
16    }
17}
18
19// Creating an object of the Book class
20$book1 = new Book("1984", "George Orwell", 9.99);
21echo $book1->getDetails(); // Outputs: Title: 1984, Author: George Orwell, Price: $9.99
22
23?>

In this example, we define a Book class with properties for the title, author, and price. The getDetails() method returns a string with the book’s details. We then create an object of the Book class and display its details.

Example: Using Inheritance

 1<?php
 2
 3class Vehicle {
 4    public $type;
 5
 6    public function __construct($type) {
 7        $this->type = $type;
 8    }
 9
10    public function getType() {
11        return "Vehicle Type: $this->type";
12    }
13}
14
15class Car extends Vehicle {
16    public $make;
17    public $model;
18
19    public function __construct($type, $make, $model) {
20        parent::__construct($type);
21        $this->make = $make;
22        $this->model = $model;
23    }
24
25    public function getCarDetails() {
26        return $this->getType() . ", Make: $this->make, Model: $this->model";
27    }
28}
29
30// Creating an object of the Car class
31$car = new Car("Sedan", "Honda", "Civic");
32echo $car->getCarDetails(); // Outputs: Vehicle Type: Sedan, Make: Honda, Model: Civic
33
34?>

In this example, the Car class inherits from the Vehicle class. The Car class adds additional properties and methods specific to cars. We use the parent::__construct() to call the parent class’s constructor.

Visualizing Classes and Objects

To better understand the relationship between classes and objects, let’s visualize it using a class diagram.

    classDiagram
	    class Car {
	        -string make
	        -string model
	        -int year
	        +__construct(string make, string model, int year)
	        +displayInfo() string
	    }
	    Car <|-- myCar

This diagram represents the Car class with its properties and methods. The myCar object is an instance of the Car class.

Key Takeaways

  • Classes are blueprints for creating objects, defining properties and methods.
  • Objects are instances of classes, each with its own values for the properties.
  • Encapsulation, abstraction, inheritance, and polymorphism are core principles of OOP.
  • Inheritance allows classes to inherit properties and methods from other classes, promoting code reuse.

Try It Yourself

Experiment with the code examples provided. Try modifying the properties and methods, or create your own classes and objects to see how they work in practice.

Knowledge Check

  1. What is a class in PHP?
  2. How do you create an object from a class?
  3. What is the purpose of a constructor in a class?
  4. Explain the concept of inheritance in PHP.
  5. How does encapsulation benefit object-oriented programming?

Exercises

  1. Define a Person class with properties for name, age, and gender. Create a method to display the person’s details.
  2. Create a Student class that inherits from the Person class. Add a property for the student’s grade and a method to display the student’s details.
  3. Experiment with creating multiple objects from the Car class and modifying their properties.

Embrace the Journey

Remember, this is just the beginning. As you progress, you’ll build more complex and interactive PHP applications. Keep experimenting, stay curious, and enjoy the journey!

Quiz: Classes and Objects in PHP

Loading quiz…
Revised on Thursday, April 23, 2026