OOP Concepts: Classes and Objects in PHP

Table of Contents

  • Introduction to Classes and Objects
  • What is a Class?
  • What is an Object?
  • How to Define and Create a Class in PHP
    • Defining a Class
    • Creating Objects
  • Accessing Object Properties and Methods
  • Using new Keyword in Object Creation
  • The Role of Constructors and Destructors
  • Example: Building a Simple Class and Object
  • Practical Application: Creating a Class for a Car
  • Summary

Introduction to Classes and Objects

In Object-Oriented Programming (OOP), two fundamental concepts are classes and objects. These concepts provide the foundation for building modular, reusable, and maintainable code. Understanding these concepts is essential for any PHP developer who wishes to embrace OOP principles in their projects.

  • Classes: A class is a blueprint for creating objects. It defines properties (attributes) and methods (functions) that an object created from that class will have.
  • Objects: An object is an instance of a class. It represents a real-world entity and has its own unique data and behavior based on the class definition.

Classes and objects help organize code in a structured manner, making it easier to manage and extend applications. In PHP, classes and objects are pivotal in structuring complex applications, especially when working with large codebases.


What is a Class?

A class is essentially a template or blueprint for creating objects. It encapsulates the properties (variables) and methods (functions) that define the behavior of the objects. You can think of a class as a mold from which multiple objects can be created, each with its own unique data but sharing the same structure and behavior.

A class typically includes:

  • Properties: Variables that store the data of an object.
  • Methods: Functions that define the behavior of the object, interacting with its properties or performing actions.

Syntax to define a class:

class ClassName {
// Properties
public $propertyName;

// Methods
public function methodName() {
// Method logic
}
}

What is an Object?

An object is an instance of a class. When a class is defined, no memory is allocated, and no functionality is executed. Only when an object is created from the class is memory allocated, and the class methods and properties come to life. Each object has its own unique set of data, even though the structure (the class) is shared.

You can think of an object as a concrete example of the class. If the class is a blueprint for a car, an object would represent an actual car.

Syntax to create an object:

$objectName = new ClassName();

How to Define and Create a Class in PHP

In PHP, defining and creating a class is simple. We define a class using the class keyword, followed by the class name. The class can have properties and methods that define the behavior of its objects.

Defining a Class

Let’s define a basic class named Car:

<?php
class Car {
// Properties
public $make;
public $model;
public $color;

// Method
public function start() {
echo "The $this->color $this->make $this->model is starting.\n";
}
}
?>

In this example, the Car class has three properties: $make, $model, and $color. It also has one method, start(), which prints a message indicating that the car is starting.

Creating Objects

Once we have a class, we can create objects of that class using the new keyword:

<?php
// Creating an object of the Car class
$myCar = new Car();
$myCar->make = "Toyota";
$myCar->model = "Corolla";
$myCar->color = "red";

// Calling the method on the object
$myCar->start();
?>

In this example:

  • We created an object $myCar of the class Car.
  • We assigned values to the properties of $myCar (make, model, color).
  • We called the start() method on the object, which uses the properties to print a message.

Accessing Object Properties and Methods

Once an object is created, you can access its properties and methods using the object’s name, followed by the arrow operator (->). This operator is used to access both properties and methods of the object.

Accessing properties:

$objectName->propertyName;

Calling methods:

$objectName->methodName();

Example:

<?php
class Person {
public $name;
public $age;

public function introduce() {
echo "Hello, my name is $this->name and I am $this->age years old.\n";
}
}

$person1 = new Person();
$person1->name = "John";
$person1->age = 30;
$person1->introduce();
?>

Using the new Keyword in Object Creation

The new keyword is used to create a new object from a class. When you instantiate an object using new, PHP allocates memory for the object and invokes the constructor (if defined).

Example:

$objectName = new ClassName();

The new keyword creates an instance of the class ClassName, and the resulting object is stored in the variable $objectName.


The Role of Constructors and Destructors

In OOP, constructors and destructors are special methods that are automatically invoked when an object is created or destroyed.

  • Constructor (__construct): This method is called when a new object is instantiated. It is commonly used to initialize object properties or set up initial states.
  • Destructor (__destruct): This method is called when an object is no longer needed or goes out of scope. It is often used for cleanup tasks like closing database connections.

Example:

<?php
class Car {
public $make;
public $model;

// Constructor method
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}

// Destructor method
public function __destruct() {
echo "The $this->make $this->model is being destroyed.\n";
}

public function displayInfo() {
echo "Car make: $this->make, Model: $this->model\n";
}
}

// Creating an object
$car1 = new Car("Toyota", "Camry");
$car1->displayInfo();

// The object will be destroyed when it goes out of scope
?>

Example: Building a Simple Class and Object

Let’s go a step further and build a class to represent a Book in a library.

<?php
class Book {
// Properties
public $title;
public $author;
public $genre;
public $yearPublished;

// Constructor
public function __construct($title, $author, $genre, $yearPublished) {
$this->title = $title;
$this->author = $author;
$this->genre = $genre;
$this->yearPublished = $yearPublished;
}

// Method to display book details
public function displayDetails() {
echo "Title: $this->title\n";
echo "Author: $this->author\n";
echo "Genre: $this->genre\n";
echo "Year Published: $this->yearPublished\n";
}
}

// Create an object
$book1 = new Book("To Kill a Mockingbird", "Harper Lee", "Fiction", 1960);
$book1->displayDetails();
?>

In this example, we have a Book class with a constructor and a method that displays the details of the book. We then create an object $book1 from the Book class, populate its properties, and call the displayDetails() method.


Practical Application: Creating a Class for a Car

To better understand classes and objects, let’s look at a practical example of a class for representing a car:

<?php
class Car {
public $make;
public $model;
public $color;

public function __construct($make, $model, $color) {
$this->make = $make;
$this->model = $model;
$this->color = $color;
}

public function start() {
echo "The $this->color $this->make $this->model is starting.\n";
}

public function stop() {
echo "The $this->color $this->make $this->model has stopped.\n";
}
}

// Creating an object of the Car class
$myCar = new Car("Honda", "Civic", "Blue");
$myCar->start();
$myCar->stop();
?>

This class defines the properties and methods for a car, such as make, model, color, and methods like start() and stop().


Summary

In this module, we explored the concepts of classes and objects in PHP, which form the foundation of Object-Oriented Programming (OOP). We discussed how to define a class, create objects, and access properties and methods. Additionally, we explored the role of constructors and destructors in initializing and cleaning up objects. By understanding and using these core OOP concepts, PHP developers can create more organized, modular, and maintainable code.