Classes and Objects in PHP

Classes and Objects

Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries, we'll start from the basics.

Classes and objects are the building blocks of OOP. A class acts as a blueprint for creating objects, which are instances of the class. Understanding these basics is essential before moving on to more advanced OOP topics like inheritance, polymorphism, and encapsulation.

What You'll Learn

In this lesson, you'll learn how to define and use classes and objects in PHP. We'll cover:

  1. Declaring and Defining Classes
  2. Creating Objects from Classes
  3. Using Constructors and Cloning Objects

Declaring and Defining Classes

In PHP, a class is defined using the class keyword. Here's a simple example:

PHP
<?php

// Defining a class named Person
class Person {
    public $name;
    public $age;

    // Constructor that initializes the object with a name and age
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    // Method to display the object's data
    public function display() {
        echo "Name: " . $this->name . ", Age: " . $this->age . "\n";
    }
}

?>

In this snippet, we define a Person class with the data members name and age and a member function display, which prints the object's data.

A constructor is a special function within a class that is automatically called when an instance of the class is created. This function is used to initialize the object’s properties with specific values. In PHP, the constructor method is defined using the __construct function.

This constructor will be triggered as soon as a new Person object is created using the new keyword. It sets the name and age of the Person instance to the values provided as arguments.

Creating Objects from Classes

Once you have defined a class, you can create objects (instances of the class). Here’s how we can create and use objects of the Person class:

PHP
<?php

$person = new Person("Alice", 30);  // Creating an object
$person->display();                 // Displaying the object's data

$personCopy = clone $person;        // Cloning the object
$personCopy->display();             // Displaying the cloned object's data

?>

Here, we create an object, $person, with the name "Alice" and age 30, and another object, $personCopy, which is a clone of the first object. Both objects display their data using the display method.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal