EZ

Eduzan

Learning Hub

Eduzan
Eduzan / PHP

PHP OOPs

Worked examples are fully visible. Check-yourself items are study aids you can reveal one at a time.

Like C++ and Java, PHP supports object-oriented programming (OOP). Classes in PHP are the blueprints for creating objects. One key difference between functions and classes is that a class can contain both data (properties/variables) and functions (methods) that define the behavior of an object.

A class is essentially a programmer-defined data type that includes local methods and properties. It serves as a collection of objects, each having specific attributes and behavior.

Syntax:

To define a class, start with the keyword class followed by the name of the class.

<?php
    class ExampleClass {

    }
?>

Note: Classes are enclosed using curly braces {}, similar to how functions are defined.

Below are examples illustrating the use of classes in PHP’s object-oriented programming:

Example 1: Constructor in PHP Class

A constructor is a special method that gets called automatically when an object of the class is created. In PHP, constructors are defined using __construct().

<?php
class MyClass
{
    // Constructor
    public function __construct(){
        echo 'The class "' . __CLASS__ . '" has been instantiated!<br>';
    }

}

// Create a new object of the class
$obj = new MyClass;
?>

Output:

The class "MyClass" has been instantiated!

Example 2: Destructor in PHP Class

A destructor is another special method that is invoked automatically when an object is no longer in use or the script execution ends. In PHP, destructors are defined using __destruct().

<?php
class MyClass
{
    // Destructor
    public function __destruct(){
        echo 'The class "' . __CLASS__ . '" has been destroyed!';
    }

}

// Create a new object of the class
$obj = new MyClass;
?>

Output:

The class "MyClass" has been destroyed!
End of lesson.