PHP OOP – Classes and Objects

Welcome to The Coding College! In this tutorial, we’ll dive into Classes and Objects in PHP. These are the foundational building blocks of Object-Oriented Programming (OOP). By mastering them, you can write structured, reusable, and maintainable code.

What Are Classes and Objects?

Class:

A class is a blueprint or template for creating objects. It defines properties (data) and methods (functions) that the objects created from the class will have.

Object:

An object is an instance of a class. It is created based on the structure defined by the class and has its own values for the properties.

Example of Class and Object

<?php
// Define a Class
class Car {
    // Properties
    public $brand;
    public $color;

    // Method
    public function start() {
        return "The car is starting...";
    }
}

// Create an Object
$myCar = new Car();

// Assign values to properties
$myCar->brand = "Toyota";
$myCar->color = "Red";

// Access properties and methods
echo "Brand: " . $myCar->brand . "<br>"; // Output: Brand: Toyota
echo "Color: " . $myCar->color . "<br>"; // Output: Color: Red
echo $myCar->start(); // Output: The car is starting...
?>

Key Features of Classes and Objects

1. Properties and Methods

  • Properties are variables that belong to a class.
  • Methods are functions defined within a class.

Example: Properties and Methods

<?php
class Dog {
    // Properties
    public $name;
    public $breed;

    // Methods
    public function bark() {
        return "Woof! Woof!";
    }

    public function introduce() {
        return "Hi, I'm a " . $this->breed . " and my name is " . $this->name;
    }
}

$myDog = new Dog();
$myDog->name = "Buddy";
$myDog->breed = "Golden Retriever";

echo $myDog->introduce(); // Output: Hi, I'm a Golden Retriever and my name is Buddy
?>

2. $this Keyword

The $this keyword refers to the current instance of the class. It is used to access properties and methods inside the class.

Access Modifiers

PHP provides three types of access modifiers to control the visibility of properties and methods:

  1. public: Accessible from anywhere.
  2. protected: Accessible only within the class and its child classes.
  3. private: Accessible only within the class.

Example: Access Modifiers

<?php
class Person {
    public $name; // Public property
    private $age; // Private property

    // Set and get methods for the private property
    public function setAge($age) {
        $this->age = $age;
    }

    public function getAge() {
        return $this->age;
    }
}

$person = new Person();
$person->name = "John"; // Allowed
echo "Name: " . $person->name . "<br>"; // Output: Name: John

$person->setAge(30); // Allowed via a method
echo "Age: " . $person->getAge(); // Output: Age: 30
?>

Constructors and Destructors

Constructor:

A constructor is a special method that gets automatically called when an object is created. It is commonly used to initialize properties.

Syntax:

public function __construct() {
    // Code to execute when the object is created
}

Destructor:

A destructor is a special method that gets automatically called when an object is destroyed (e.g., when the script ends). It is used for cleanup tasks.

Syntax:

public function __destruct() {
    // Code to execute when the object is destroyed
}

Example: Constructor and Destructor

<?php
class Laptop {
    public $brand;

    // Constructor
    public function __construct($brand) {
        $this->brand = $brand;
        echo "A new laptop of brand $this->brand has been created.<br>";
    }

    // Destructor
    public function __destruct() {
        echo "The laptop of brand $this->brand is now destroyed.<br>";
    }
}

$laptop1 = new Laptop("Dell");
// Output: A new laptop of brand Dell has been created.

// The destructor will run automatically when the object is no longer needed.
?>

Methods in Classes

Static Methods

Static methods belong to the class rather than to any object. They can be accessed without creating an object.

Example: Static Methods

<?php
class MathUtils {
    public static function add($a, $b) {
        return $a + $b;
    }
}

// Access the static method without creating an object
echo "Sum: " . MathUtils::add(5, 3); // Output: Sum: 8
?>

Example: Combining Static and Regular Methods

<?php
class Counter {
    private static $count = 0;

    public static function increment() {
        self::$count++;
    }

    public static function getCount() {
        return self::$count;
    }
}

// Call static methods
Counter::increment();
Counter::increment();
echo "Count: " . Counter::getCount(); // Output: Count: 2
?>

Example: Real-World Application

Let’s create a User Management System using classes and objects.

<?php
class User {
    public $username;
    private $password;

    // Constructor to initialize user details
    public function __construct($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }

    // Method to check login
    public function login($username, $password) {
        if ($this->username === $username && $this->password === $password) {
            return "Login successful! Welcome, " . $this->username;
        } else {
            return "Invalid username or password.";
        }
    }
}

// Create a new user
$user1 = new User("admin", "password123");

// Login attempt
echo $user1->login("admin", "password123"); // Output: Login successful! Welcome, admin
?>

Benefits of Classes and Objects in PHP

  1. Code Reusability: You can create multiple objects from the same class.
  2. Modularity: Break down large applications into smaller, manageable components.
  3. Easy Maintenance: Update or modify the class without affecting the objects.
  4. Encapsulation: Protect sensitive data by using private and protected access modifiers.

Conclusion

Classes and objects are the core of Object-Oriented Programming in PHP. By understanding how to define classes, create objects, and use features like access modifiers, constructors, and methods, you can write clean and maintainable code.

For more PHP tutorials and coding guides, check out The Coding College.

Leave a Comment