Sling Academy
Home/PHP/Understanding PHP class constructors: A practical guide

Understanding PHP class constructors: A practical guide

Last updated: January 10, 2024

Overview

Class constructors in PHP are critical for object-oriented programming, providing a straightforward way to initialize object properties and execute initial setup tasks. This guide walks you through the practical application of PHP constructors, from basic usage to more advanced patterns.

Introduction to Constructors

Constructors are special methods within a class that are automatically called when a new instance of the class is created. In PHP, a constructor is defined using the __construct method.

<?php

class SampleClass {
    public function __construct() {
        echo 'Object created!';
    }
}

$instance = new SampleClass(); // Output: Object created!

?>

Passing Parameters to Constructors

PHP class constructors can accept parameters, which allow for dynamic initialization of object properties upon creation.

<?php

class User {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }
    public function greet() {
        return 'Hello, ' . $this->name . '!';
    }
}

$user = new User('John');

echo $user->greet(); // Output: Hello, John!

?>

Enforcing Class Properties

Constructors can enforce class properties and types to ensure a consistent object state upon instantiation.

<?php

class Product {
    protected $name;
    protected $price;

    public function __construct(string $name, float $price) {
        $this->setName($name);
        $this->setPrice($price);
    }

    public function displayInfo() {
        return $this->name . ' costs $' . number_format($this->price, 2);
    }

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

    public function setPrice(float $price) {
        if ($price < 0) {
            throw new InvalidArgumentException('Price cannot be negative.');
        }

        $this->price = $price;
    }
}

$product = new Product('Coffee', 4.99);

try {
    // Set an invalid price to demonstrate exception handling
    $product->setPrice(-1);
} catch (InvalidArgumentException $e) {
    echo 'Exception: ' . $e->getMessage() . PHP_EOL;
}

echo $product->displayInfo(); 
// Output: Coffee costs $4.99

Constructors in Inheritance

Constructors also play a significant role in class inheritance. A subclass constructor must explicitly call its parent’s constructor if it is defined.

<?php

class BaseClass {
    public function __construct() {
        echo 'Base class constructor called';
    }
}

class SubClass extends BaseClass {
    public function __construct() {
        parent::__construct();
        echo 'Subclass constructor called';
    }
}

$sub = new SubClass();
// Output: Base class constructor called
// Output: Subclass constructor called

?>

Advanced Constructor Usage

For more complex scenarios, PHP constructors can encompass additional patterns such as Dependency Injection, Factory Methods, and Singleton patterns.

<?php

class DatabaseConnection {
    protected $connection;
    public function __construct($host, $user, $pass, $db) {
        $this->connection =  new mysqli($host, $user, $pass, $db);
    }

    // Other database related methods
}

class UserDB {

    protected $dbConnection;

    public function __construct(DatabaseConnection $connection) {
        $this->dbConnection = $connection;
    }

    // Methods to interact with the user-related data in the database
}

$dbConnection = new DatabaseConnection('localhost', 'username', 'password', 'myDatabase');
$userDB = new UserDB($dbConnection); 

echo ($userDB->checkConnection() ? 'Connected':'Failed to connect'); // Example output - usage of the connected object

?>

Conclusion

In summary, understanding and using PHP class constructors effectively can profoundly impact your object-oriented programming in PHP. This guide has provided practical examples and patterns to leverage constructors’ full potential, equipping you to write cleaner, more maintainable code.

Next Article: Understanding the ‘this’ keyword in PHP classes: A detailed guide

Previous Article: PHP class static properties and methods: A complete guide

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array