PHP & MySQL

PHP OOP - Constructor Method (__construct)

Complete guide to PHP constructors -__construct() syntax, parameter promotion, inheritance with parent::__construct(), dependency injection, and best practices.

Basic Constructor

<?php
class User {
    public string $name;
    public string $email;

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

    public function greet(): string {
        return "Hello, {$this->name}!";
    }
}

$user = new User('Alice', 'alice@example.com');
echo $user->greet();  // "Hello, Alice!"

Constructor Promotion (PHP 8.0+)

PHP 8 introduced constructor promotion - declare and assign properties in the constructor signature:

<?php
class User {
    // Properties are declared AND assigned automatically
    public function __construct(
        public string $name,
        public string $email,
        public string $role = 'member',
        private ?string $passwordHash = null,
    ) {
        // Additional initialization if needed
    }
}

$user = new User('Alice', 'alice@example.com', 'admin');
echo $user->name;  // "Alice"
echo $user->role;  // "admin"

Constructor Inheritance

<?php
class Animal {
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

class Dog extends Animal {
    public function __construct(
        string $name,
        int $age,
        public string $breed
    ) {
        // Call parent constructor
        parent::__construct($name, $age);
    }

    public function info(): string {
        return "{$this->name} is a {$this->age}yr {$this->breed}";
    }
}

$dog = new Dog('Rex', 3, 'Labrador');
echo $dog->info();  // "Rex is a 3yr Labrador"

Default Values & Optional Parameters

<?php
class Config {
    public function __construct(
        private string $host = 'localhost',
        private int $port = 3306,
        private string $charset = 'utf8mb4',
        private bool $debug = false,
    ) {}

    public function dsn(): string {
        return "mysql:host={$this->host};port={$this->port};charset={$this->charset}";
    }
}

// Use defaults
$default = new Config();

// Override specific values with named arguments (PHP 8.0+)
$custom = new Config(host: 'db.example.com', debug: true);

Dependency Injection via Constructor

<?php
interface Logger {
    public function log(string $message): void;
}

class FileLogger implements Logger {
    public function __construct(private string $path) {}
    public function log(string $message): void {
        file_put_contents($this->path, date('c') . " $message\n", FILE_APPEND);
    }
}

class UserService {
    public function __construct(
        private PDO $db,
        private Logger $logger,
    ) {}

    public function create(string $name, string $email): int {
        $stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        $stmt->execute([$name, $email]);
        $id = (int) $this->db->lastInsertId();
        $this->logger->log("Created user #$id: $name");
        return $id;
    }
}

// Wire dependencies
$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$logger = new FileLogger('/var/log/app.log');
$service = new UserService($pdo, $logger);

Readonly Properties (PHP 8.1+)

<?php
class Immutable {
    public function __construct(
        public readonly string $id,
        public readonly string $name,
        public readonly DateTimeImmutable $createdAt,
    ) {}
}

$obj = new Immutable('abc', 'Test', new DateTimeImmutable());
echo $obj->name;     // "Test"
// $obj->name = 'X'; // Error: Cannot modify readonly property

Last updated: 2026 • Browse all courses