PHP Objects 5: All you should know About PHP OOP

PHP Objects 5 All you should know About PHP OOP
PHP Objects 5 All you should know About PHP OOP

To start with, let’s dive into “Final Classes and Methods,” which delves into the use and implications of the final keyword in PHP Objects to restrict inheritance and method overriding.


PHP Objects 4: Highlights

Before delving into the details, it’s helpful to review our previous guide, “PHP Objects 4: All you should know about PHP OOP.” In this article, we explore the use of getters and setters in PHP, focusing on controlled property access, their advantages, and practical applications. Additionally, we dive into static properties and methods, showcasing how they facilitate shared resources and enhance object-oriented efficiency, with the help of several examples.


Final Classes and Methods in PHP: Restricting Inheritance and Overriding

The final keyword in PHP is a powerful tool for object-oriented programming that allows you to restrict the inheritance of classes and prevent the overriding of methods. Therefore In this section, we’ll delve into the concept of final classes and methods, their usage, and their implications.

Final Classes: Inheritance Restriction

A final class is a class that you cannot extend any further. When you mark a class as final, you prevent other classes from inheriting from it. This prevents alteration and protects the core functions of a class from unauthorized or unintentional changes.

Example (Final Class):

final class Configuration {
    // Class implementation
}

// Attempting to extend a final class will result in an error
// class CustomConfiguration extends Configuration {}

Looking at this example, we declare the Configuration class as final, indicating none can extend it. Any attempt to create a subclass of Configuration will result in an error.

Final Methods: Overriding Prevention

A final method is a method that subclasses cannot override eventually or intentionally. When you mark a method as final, you ensure that the method’s behavior remains consistent across all subclasses.

Example (Final Method):

class ParentClass {
    public final function importantOperation() {
        // Method implementation
    }
}

class ChildClass extends ParentClass {
    // Attempting to override a final method will result in an error
    // public function importantOperation() {}
}

Observing this example, the importantOperation method in ParentClass is the final. There Any attempt to override this method in a subclass, such as ChildClass, will result in an error.

Use Cases for Final Members

Shortly Final classes and methods are for various reasons, including:

  1. Security: Final classes can protect sensitive or critical functionality from unintended modifications.
  2. API Stability: Final methods ensure that critical API methods retain their behavior, maintaining compatibility for all subclasses.
  3. Design Contracts: Final members indicate that specific parts of the class must remain as-is and not extended or modified.
  4. Performance Optimization: Final methods can help optimize performance in specific use cases.

Object-Oriented Design Principles

Using the final keyword in your PHP code follows the principles of encapsulation and consistency. It promotes robust software design by safeguarding core functionality and preventing unintentional changes.

Meanwhile By carefully choosing where to apply the final keyword, you can improve the maintainability and reliability of your object-oriented PHP code.


To sum it up, this article provides insight into the concept of final classes and methods in PHP. It emphasizes their role in limiting inheritance and preventing method overriding.

Now and shortly, let’s provide more examples to illustrate the usage of final classes and methods in PHP.

Example 1: Final Class for a Core Library

Using a Final Class for a Core Library:

final class CoreLibrary {
    public function coreFunction() {
        return 'This is a core library function.';
    }
}

// Attempting to extend a final class will result in an error
// class CustomLibrary extends CoreLibrary {}

$coreLibrary = new CoreLibrary();
$result = $coreLibrary->coreFunction();

In this example, the CoreLibrary class is the final, ensuring that its extension is impossible. It represents a core library with essential functions, therefore subclasses cannot override its coreFunction method.

Example 2: Final Method for a Critical Operation

Using a Final Method for a Critical Operation:

class Database {
    public function connect() {
        // Database connection logic
        return 'Connected to the database.';
    }

    final public function disconnect() {
        // Database disconnection logic
        return 'Disconnected from the database.';
    }
}

class CustomDatabase extends Database {
    // Attempting to override a final method will result in an error
    // public function disconnect() {}
}

$database = new Database();
$result = $database->disconnect(); // $result will be 'Disconnected from the database.'

In this example, the Database class contains a disconnect method marked as final. This ensures that the disconnection operation remains consistent across all instances and subclasses.

Example 3: Final Method in a Framework

Using a Final Method in a Framework:

class FrameworkComponent {
    public function initialize() {
        // Initialization logic
        return 'Component initialized.';
    }
}

class CustomComponent extends FrameworkComponent {
    final public function initialize() {
        // Custom initialization logic
        return 'Custom component initialized.';
    }
}

$frameworkComponent = new FrameworkComponent();
$customComponent = new CustomComponent();

$result1 = $frameworkComponent->initialize(); // $result1 will be 'Component initialized.'
$result2 = $customComponent->initialize(); // $result2 will be 'Custom component initialized.'

In this example, the FrameworkComponent class contains an initialize method marked as final. The CustomComponent class attempts to override the method but can only provide additional functionality, ensuring that the core initialization process remains unchanged.

Example 4: Final Class for a Singleton Pattern

Using a Final Class for Singleton Pattern:

final class Singleton {
    private static $instance;

    final public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {}
}

$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();

// $singleton1 and $singleton2 point to the same instance

In this example, the Singleton class is final and follows the Singleton pattern. This Also ensures that you that you can create and share only one instance of the class across the application.

These examples demonstrate the practical use of final classes and methods in PHP. They provide an effective way to safeguard core functionality, maintain consistent behavior, and design classes with specific intended use.

Moving forward, we will explore “Magic Methods,” a topic that delves into the special methods in PHP, often referred to as magic methods. These methods enable you to define how an object behaves in response to specific actions.


Magic Methods in PHP: Unleashing Object Wizardry

Magic methods in PHP serve as specialized tools that empower you to customize and enhance the behavior of your objects in response to specific actions. Moreover, these methods play an integral role in object-oriented programming, as they facilitate operations such as object construction, property access, and method invocation with finesse. With this understanding as a backdrop, let’s now explore the fascinating realm of PHP magic methods in the forthcoming section.

The Magic Methods Lineup

PHP provides a set of magic methods that triggers under specific circumstances. Here are some of the most common magic methods that are mostly in use today:

  1. __construct: You call this method immediately you create an object and allows you to initialize its properties.
  2. __destruct: You Invoke it when your destroy an object, typically at the end of a script or when no references to the object exist.
  3. __get: Called when trying to access a property that is not accessible, allowing you to define custom behavior.
  4. __set: Invoked when trying to set the value of an inaccessible property, enabling you to control property assignments.
  5. __isset: Triggered when checking if a property exists using the isset function.
  6. __unset: Called when attempting to unset an inaccessible property using the unset function.
  7. __call: Invoked when calling a method that is not accessible or does not exist.
  8. __callStatic: Similar to __call, but for static methods.
  9. __toString: Defines how an object should behave when treated as a string using the echo or print statements.

Customizing Object Behavior

Magic methods allow you to create objects that respond to actions in a way that is meaningful for your application. Here’s an example using the __get and __set magic methods:

Example (Custom Property Access):

class DynamicProperty {
    private $data = [];

    public function __get($name) {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        } else {
            return "Property '$name' does not exist.";
        }
    }

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

$dynamic = new DynamicProperty();
$dynamic->customProperty = "Hello, Magic!";
$propertyValue = $dynamic->customProperty; // $propertyValue will be 'Hello, Magic!'
$nonExistentProperty = $dynamic->nonExistent; // $nonExistentProperty will be 'Property 'nonExistent' does not exist.'

In this example, the __get and __set magic methods allow custom property access for the DynamicProperty class.

Practical Applications

Magic methods are frequently used for a variety of tasks, including creating flexible class constructors, managing dynamic properties, intercepting method calls, and more. They introduce a layer of versatility to your objects, allowing them to adapt to specific use cases and scenarios.

Furthermore, magic methods form a fundamental part of PHP’s object-oriented features. With magic methods, you can create objects with dynamic behaviors tailored to your application’s requirements.


In summary an overview of magic methods in PHP, explaining their significance and demonstrating how they can you can customize object behavior.

Certainly, let’s provide more examples to illustrate the usage of various magic methods in PHP.

Example 1: Custom Constructor with __construct

Custom Constructor Using __construct:

class Person {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

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

$person = new Person('John');
$intro = $person->introduce(); // $intro will be "Hi, I'm John."

In this example, the __construct method is used to create a custom constructor for the Person class, allowing you to initialize the object with a name.

Example 2: Custom Property Access with __get

Custom Property Access Using __get:

class DynamicProperty {
    private $data = [];

    public function __get($name) {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        } else {
            return "Property '$name' does not exist.";
        }
    }
}

$dynamic = new DynamicProperty();
$dynamic->customProperty = "Hello, Magic!";
$propertyValue = $dynamic->customProperty; // $propertyValue will be 'Hello, Magic!'
$nonExistentProperty = $dynamic->nonExistent; // $nonExistentProperty will be 'Property 'nonExistent' does not exist.'

Here, the __get method is used to enable custom property access for the DynamicProperty class, including handling non-existent properties gracefully.

Example 3: Custom Method Invocation with __call

Custom Method Invocation Using __call:

class MathOperation {
    public function __call($name, $arguments) {
        if ($name === 'add') {
            return array_sum($arguments);
        } elseif ($name === 'multiply') {
            return array_product($arguments);
        }
    }
}

$math = new MathOperation();
$result1 = $math->add(2, 3, 5); // $result1 will be 10
$result2 = $math->multiply(2, 3, 5); // $result2 will be 30

In this example, the __call method is used to create a dynamic math operation class that can handle both addition and multiplication with variable numbers of arguments.

These examples showcase the versatility of magic methods in PHP, enabling you to create objects with custom constructors, dynamic property access, and even handle method calls not explicitly defined in the class. Magic methods enhance the adaptability and flexibility of your PHP objects.

Moving on let’s continue with “Construct and Destruct,” which focuses on the __construct and __destruct magic methods in PHP, explaining how they are used to initialize and clean up objects.


Construct and Destruct: The Building and Demolition of PHP Objects

In PHP, the __construct and __destruct methods are essential magic methods that define the initialization and cleanup processes of objects. Creating and destroying an object, respectively calls these methods are automatically. In this section, we’ll explore the roles of __construct and __destruct in managing PHP objects.

The Constructor: __construct

The __construct method is a magic method used to initialize an object when it is created. It allows you to perform any setup tasks, such as initializing properties or establishing connections, to prepare the object for use.

Example (Using __construct):

class Book {
    private $title;

    public function __construct($title) {
        $this->title = $title;
        echo "Book '$title' is created.<br>";
    }

    public function getTitle() {
        return $this->title;
    }
}

$book = new Book('The Great Gatsby');
$title = $book->getTitle();

In this example, the __construct method is used to set the title of a book when the object is created. The constructor is automatically called when the $book object is instantiated.

The Destructor: __destruct

The __destruct method is another magic method that is called when an object is no longer referenced or explicitly destroyed. Also It allows you to perform cleanup tasks, release resources, or log actions before one removes the object from memory.

Example (Using __destruct):

class Logger {
    private $logFile;

    public function __construct($logFile) {
        $this->logFile = $logFile;
        echo "Logger initialized.<br>";
    }

    public function log($message) {
        file_put_contents($this->logFile, $message . PHP_EOL, FILE_APPEND);
    }

    public function __destruct() {
        echo "Logger destroyed.<br>";
    }
}

$logger = new Logger('app.log');
$logger->log('An event occurred');
unset($logger); // Destroying the object

In this example, the __destruct method is used to log a message and signal that the logger is being destroyed. When the object is explicitly destroyed using unset($logger), the destructor is called.

Utilizing Construct and Destruct

The __construct and __destruct methods are valuable for various tasks, including:

  1. Resource Management: Initializing and releasing resources like database connections, file handles, and network connections.
  2. Logging and Monitoring: Logging actions or events during object lifecycle for debugging and monitoring purposes.
  3. Setup and Cleanup: Setting up and cleaning up object-specific configurations.
  4. Memory Optimization: Releasing memory and resources when objects are no longer necessary.

These methods are essential in building and managing PHP objects, ensuring proper initialization and cleanup in your applications.


This content explains the roles of __construct and __destruct in PHP, detailing how they are used to initialize and clean up objects.

Furthermore, let’s provide more examples to illustrate the usage of __construct and __destruct methods in PHP.

Example 1: Resource Management with __construct and __destruct

Managing Database Connections:

class DatabaseConnection {
    private $connection;

    public function __construct($host, $username, $password, $database) {
        $this->connection = new mysqli($host, $username, $password, $database);
        if ($this->connection->connect_error) {
            die('Connection failed: ' . $this->connection->connect_error);
        }
        echo 'Database connection established.<br>';
    }

    public function query($sql) {
        $result = $this->connection->query($sql);
        return $result->fetch_assoc();
    }

    public function __destruct() {
        $this->connection->close();
        echo 'Database connection closed.<br>';
    }
}

$db = new DatabaseConnection('localhost', 'username', 'password', 'my_database');
$result = $db->query('SELECT * FROM users');

In this example, the __construct method establishes a database connection, and the __destruct method closes the connection when the object is destroyed.

Example 2: Logging with __construct and __destruct

Logging Actions:

class ActionLogger {
    private $logFile;

    public function __construct($logFile) {
        $this->logFile = $logFile;
        echo 'Logger initialized.<br>';
    }

    public function log($message) {
        file_put_contents($this->logFile, $message . PHP_EOL, FILE_APPEND);
        echo "Logged: $message<br>";
    }

    public function __destruct() {
        echo 'Logger destroyed.<br>';
    }
}

$logger = new ActionLogger('activity.log');
$logger->log('User login');
$logger->log('Data saved');
unset($logger); // Destroying the object

Here, the __construct method initializes a logger, the log method records actions, and the __destruct method logs that the logger is being destroyed.

These examples demonstrate how __construct and __destruct methods can be used for resource management, logging, and performing setup and cleanup tasks, enhancing the adaptability and functionality of PHP objects.

Moreover the next discussion is on PHP “Get and Set,” which focuses on using the __get and __set magic methods in PHP to customize property access and assignment.


Get and Set: Customizing Property Access and Assignment in PHP

In PHP, the __get and __set magic methods provide a powerful way to customize how properties are accessed and assigned within objects. These methods enable you to define specific behavior for property access and assignment, making your objects more flexible and adaptable. In this section, we’ll delve into the world of custom property access and assignment with __get and __set.

Custom Property Access: __get

The __get magic method is called when an attempt is made to access a property that is not accessible or does not exist within an object. It allows you to define custom behavior, such as retrieving property values from hidden data structures or providing computed values.

Example (Using __get):

class DynamicProperty {
    private $data = [];

    public function __get($name) {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        } else {
            return "Property '$name' does not exist.";
        }
    }
}

$dynamic = new DynamicProperty();
$dynamic->customProperty = "Hello, Magic!";
$propertyValue = $dynamic->customProperty; // $propertyValue will be 'Hello, Magic!'
$nonExistentProperty = $dynamic->nonExistent; // $nonExistentProperty will be 'Property 'nonExistent' does not exist.'

In this example, the __get method allows custom property access for the DynamicProperty class, including handling non-existent properties gracefully.

Custom Property Assignment: __set

The __set magic method is called when an attempt is made to set the value of an inaccessible property or a property that does not exist. It allows you to control property assignments, enabling you to validate or process data before you store it.

Example (Using __set):

class DataValidator {
    private $data = [];

    public function __set($name, $value) {
        if (is_numeric($value)) {
            $this->data[$name] = $value;
        } else {
            echo "Invalid value for property '$name'. Only numeric values allowed.<br>";
        }
    }
}

$validator = new DataValidator();
$validator->age = 30; // Valid
$validator->score = 'A'; // Invalid value for property 'score'. Only numeric values allowed.

In this example, the __set method is used to validate and control property assignments for the DataValidator class, ensuring that only numeric values are stored.

Practical Applications

Custom property access and assignment with __get and __set are valuable for various tasks, including:

  1. Data Validation: Ensuring that data stored in properties meets specific criteria or restrictions.
  2. Virtual Properties: Creating computed or virtual properties based on existing data.
  3. Property Encapsulation: Implementing encapsulation and controlled access to object data.
  4. Dynamic Behavior: Modifying or extending property access and assignment based on runtime conditions.

These methods add a layer of flexibility and control to your PHP objects, allowing them to adapt to specific use cases and scenarios.


Also the usage of __get and __set magic methods in PHP, detailing how they enable custom property access and assignment.

Besides, we will explore more examples to provide a comprehensive understanding of how to use the __get and __set magic methods in PHP.

Example 1: Virtual Properties with __get

Creating a Virtual Property Using __get:

class Circle {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function __get($name) {
        if ($name === 'area') {
            return round(pi() * pow($this->radius, 2), 2);
        }
    }
}

$circle = new Circle(5);
$circleArea = $circle->area; // Accessing the virtual property 'area'

In this example, the __get method is used to create a virtual property ‘area’ for the Circle class, which calculates and returns the area of the circle.

Example 2: Data Validation with __set

Data Validation Using __set:

class User {
    private $username;
    private $email;

    public function __set($name, $value) {
        if ($name === 'username') {
            // Ensure the username is at least 5 characters long
            if (strlen($value) >= 5) {
                $this->username = $value;
            } else {
                echo 'Username must be at least 5 characters long.<br>';
            }
        } elseif ($name === 'email') {
            // Ensure the email is valid
            if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
                $this->email = $value;
            } else {
                echo 'Invalid email address.<br>';
            }
        }
    }
}

$user = new User();
$user->username = 'john_doe'; // Valid
$user->username = 'joh'; // Username must be at least 5 characters long.
$user->email = 'johndoe@example.com'; // Valid
$user->email = 'invalid_email'; // Invalid email address.

Here, the __set method is used to validate and control property assignments for the User class, ensuring that usernames are at least 5 characters long and emails are valid.

Example 3: Dynamic Property Management with __get and __set

Dynamic Property Management:

class PropertyManager {
    private $properties = [];

    public function __get($name) {
        if (array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }
    }

    public function __set($name, $value) {
        $this->properties[$name] = $value;
    }
}

$manager = new PropertyManager();
$manager->name = 'John';
$manager->age = 30;

$propertyName = 'name';
$propertyValue = $manager->$propertyName; // Accessing a property dynamically

In this example, the __get and __set methods are used to manage properties dynamically within the PropertyManager class. You can access and assign properties using variable names.

These examples showcase how __get and __set can be used to create virtual properties, validate data, and provide dynamic property management, making your PHP objects more versatile and adaptable.

In the meantime We have concentrated much on get and set it is time to move on Inevitably part of the PHP Objects “Object String Conversion,” which focuses on using the __toString magic method in PHP to customize how objects are converted to strings.

Object String Conversion: Making PHP Objects Speak Your Language

In PHP, the __toString magic method empowers you to define how an object should behave when it is treated as a string. This allows you to create meaningful and informative representations of your objects. In this section, we’ll explore the concept of object string conversion with __toString.

The __toString Magic Method

The __toString method is called when you attempt to treat an object as a string using the echo or print statements. It provides a way to control the string representation of your objects, making them more user-friendly or facilitating debugging.

Example (Using __toString):

class Product {
    private $name;
    private $price;

    public function __construct($name, $price) {
        $this->name = $name;
        $this->price = $price;
    }

    public function __toString() {
        return "Product: {$this->name}, Price: \${$this->price}";
    }
}

$product = new Product('Smartphone', 499.99);
echo $product; // Object converted to a string: "Product: Smartphone, Price: $499.99"

In this example, the __toString method is used to define a custom string representation for the Product class, Also making it easier to display product information.

Practical Applications

Object string conversion with __toString is valuable for various tasks, including:

  1. User-Friendly Output: Creating human-readable representations of objects for display in web pages or user interfaces.
  2. Logging and Debugging: Facilitating debugging by providing clear and informative object information in log files.
  3. Serialization: Simplifying the serialization of objects into string formats like JSON or XML.
  4. Custom Messages: Customizing error messages or notifications with meaningful object information.
  5. Data Export: Preparing objects for data export or integration with external systems.

This method adds a layer of user-friendliness and customization to your PHP objects, allowing them to convey information in a way that suits your application’s needs.


The usage of the __toString magic method in PHP, describing how it enables custom object string conversion.

Certainly, let’s provide more examples to illustrate the usage of the __toString magic method in PHP.

Example 1: User-Friendly Object Representation

Creating a User-Friendly Object Representation:

class Contact {
    private $name;
    private $email;

    public function __construct($name, $email) {
        $this->name = $name;
        $this->email = $email;
    }

    public function __toString() {
        return "Contact Information:\nName: {$this->name}\nEmail: {$this->email}";
    }
}

$contact = new Contact('John Doe', 'john.doe@example.com');
echo $contact;

Consequently In this example, the __toString method is used to create a user-friendly representation of a Contact object. Therefore When you echo the object, it displays the contact information in a clear and readable format.

Example 2: Debugging with __toString

Simplifying Debugging with __toString:

class DebugInfo {
    private $data;

    public function __construct(array $data) {
        $this->data = $data;
    }

    public function __toString() {
        return "Debug Information:\n" . print_r($this->data, true);
    }
}

$data = ['user' => 'John', 'age' => 30, 'is_active' => true];
$debugInfo = new DebugInfo($data);
echo $debugInfo;

However, the __toString method is used to simplify the debugging process by creating a structured string representation of the data. It’s useful for logging or outputting detailed debug information.

Example 3: Custom Error Messages

Creating Custom Error Messages with __toString:

class CustomError {
    private $errorCode;
    private $errorMessage;

    public function __construct($errorCode, $errorMessage) {
        $this->errorCode = $errorCode;
        $this->errorMessage = $errorMessage;
    }

    public function __toString() {
        return "Error {$this->errorCode}: {$this->errorMessage}";
    }
}

$error = new CustomError(404, 'Page not found');
echo $error; // "Error 404: Page not found"

In this example, the __toString method is used to generate custom error messages, making it easy to display error information when needed.

These examples demonstrate how the __toString magic method can be used to create user-friendly object representations, simplify debugging, and generate custom error messages, enhancing the adaptability and functionality of PHP objects.

Afterward we let’s dive into the part six of All you should know concerning Objects.

NEXT > PHP Objects 6: All you should know About PHP OOP

LEAVE A REPLY

Please enter your comment!
Please enter your name here