PHP Classes/Objects


Classes and objects form the foundation of Object-Oriented Programming (OOP) in PHP. Understanding how to define classes, create objects, and work with their properties and methods is essential for building structured, maintainable, and scalable PHP applications.

OOP allows developers to model real-world entities in code, group related functionalities, and make applications more modular. In this tutorial, we’ll explore classes, objects, properties, methods, constructors, destructors, access modifiers, object interaction, and best practices, with examples you can follow step by step.

What is a Class?

A class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that describe the behavior and state of an object. Classes allow you to group related code together and create multiple objects that share the same structure.

Think of a class as a template: it defines what an object should have, but each object can have different values for its properties.

Example of a Class

class Car {
    public $brand;
    public $color;

    public function drive() {
        echo $this->brand . " is driving.<br>";
    }
}

Here, Car is a class with two properties (brand and color) and one method (drive()).

Creating Objects

An object is an instance of a class. You can create multiple objects from the same class, each with its own property values.

Example of Creating Objects

$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";

$car2 = new Car();
$car2->brand = "Honda";
$car2->color = "Blue";

$car1->drive(); // Outputs: Toyota is driving.
$car2->drive(); // Outputs: Honda is driving.

$this inside a class refers to the current object. It is used to access properties and methods of the object. Without $this, PHP won’t know which object’s property to refer to.

Class Properties

Properties are variables that belong to a class. They store the state of an object. In PHP, properties can have access modifiers, which define who can access them:

  • public – Accessible from anywhere.

  • protected – Accessible within the class and subclasses.

  • private – Accessible only within the class itself.

Example:

class Student {
    public $name;
    private $grade;

    public function setGrade($g) {
        $this->grade = $g;
    }

    public function getGrade() {
        return $this->grade;
    }
}

$student = new Student();
$student->name = "Alice";
$student->setGrade(90);
echo $student->getGrade(); // Outputs: 90

By using private properties and public getter/setter methods, you control how data is accessed or modified, which is a principle called encapsulation.

Class Methods

Methods are functions defined inside a class. They define the behavior of an object. Methods can also have access modifiers.

Example:

class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }

    protected function multiply($a, $b) {
        return $a * $b;
    }
}

$calc = new Calculator();
echo $calc->add(10, 5); // Outputs: 15

multiply() is protected and cannot be called directly from outside the class. It can only be used within the class or by a subclass.

Constructors

A constructor is a special method that automatically runs when an object is created. It is commonly used to initialize properties and set default values.

Example:

class Car {
    public $brand;
    public $color;

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

    public function showDetails() {
        echo $this->brand . " - " . $this->color . "<br>";
    }
}

$car = new Car("Toyota", "Red");
$car->showDetails(); // Outputs: Toyota - Red

Constructors save time and prevent repetitive code when initializing multiple objects.

Destructors

A destructor is a special method that runs when an object is destroyed or goes out of scope. It’s typically used to release resources such as closing files or database connections.

Example:

class FileHandler {
    public function __construct() {
        echo "File opened.<br>";
    }

    public function __destruct() {
        echo "File closed.<br>";
    }
}

$file = new FileHandler();

When the script ends or the object is destroyed, the destructor automatically runs, ensuring proper cleanup.

Object Interaction

Objects can interact by calling methods or passing objects as parameters. This enables modular code design.

Example:

class Person {
    public $name;

    public function greet($friend) {
        echo $this->name . " says hello to " . $friend->name . "<br>";
    }
}

$alice = new Person();
$alice->name = "Alice";

$bob = new Person();
$bob->name = "Bob";

$alice->greet($bob); // Outputs: Alice says hello to Bob

Objects can communicate, share data, and call each other’s methods, making OOP a powerful tool for real-world applications.

Common Mistakes to Avoid

  1. Forgetting $this when accessing object properties or methods.

  2. Making everything public – use private/protected properties for better encapsulation.

  3. Using global variables instead of objects – defeats the purpose of OOP.

  4. Overcomplicating small scripts – not every script needs full OOP.

Best Practices

  • Always use meaningful class and property names.

  • Keep properties private and use getters/setters.

  • Use constructors for initialization.

  • Keep methods focused on a single task.

  • Use object interaction instead of procedural code when modeling real-world entities.

Summary of the Tutorial

  • A class is a blueprint; an object is an instance.

  • Properties store the object’s state; methods define behavior.

  • Access modifiers control visibility: public, protected, private.

  • Constructors initialize objects; destructors clean up resources.

  • Objects can interact with each other, making OOP code modular, reusable, and maintainable.

Mastering classes and objects lays the foundation for advanced OOP concepts in PHP, such as inheritance, interfaces, traits, and namespaces.


Practice Questions

  1. Create a class Book with properties title, author, and price. Instantiate an object, assign values, and display all the property values.

  2. Write a PHP program to create a class Student with a method introduce() that prints the student’s name and age. Instantiate the class and call the method.

  3. Create a class Car with a private property speed. Add public methods setSpeed($s) and getSpeed() to set and get the speed. Demonstrate encapsulation by using these methods.

  4. Create a class BankAccount with properties accountNumber and private balance. Add methods deposit($amount) and withdraw($amount). Handle withdrawal attempts that exceed the balance.

  5. Create a class Person with a method greet() and a property name. Create another class Friend with a method sayHello($person) that accepts a Person object and prints a greeting.

  6. Write a PHP program to demonstrate constructors by creating a Car class. Initialize brand and color through the constructor and display the details.

  7. Create a class FileHandler with a constructor that opens a file and a destructor that closes it. Instantiate the class to observe the automatic execution of constructor and destructor.

  8. Create a class Calculator with methods add($a, $b) and subtract($a, $b). Instantiate two objects and perform different calculations.

  9. Write a PHP program to create a Student class with protected properties name and grade. Create a subclass HighSchoolStudent that adds a section property and a method to display all details.

  10. Create a class Rectangle with properties length and width and a method area(). Create a subclass Square that inherits from Rectangle and sets both length and width to the same value. Calculate and display the area for both classes.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top