Constructors and Destructors
Constructors are one of the most important concepts in Object Oriented Programming.
Almost every framework heavily relies on constructors.
Examples:
- PocketMine-MP
- Laravel
- Symfony
- APIs
- Dependency Injection Containers
- Enterprise Applications
What is a Constructor?
A constructor is a special method that automatically runs when an object is created.
Example:
$player =
new Player();
Immediately after:
new Player()
PHP automatically executes:
__construct()
Constructor Lifecycle
new Player()
↓
Memory Allocated
↓
__construct()
↓
Object Ready
Constructor Syntax
class Player {
public function __construct() {
echo "Player Created";
}
}
Example
$player =
new Player();
Output:
Player Created
Why Constructors Exist
Without constructors:
$player =
new Player();
$player->name =
"Aayan";
$player->money =
5000;
$player->rank =
"Owner";
This becomes repetitive.
Constructors solve this.
Constructor Parameters
class Player {
public string $name;
public function __construct(
string $name
) {
$this->name =
$name;
}
}
Usage
$player =
new Player(
"Aayan"
);
Visualization
new Player("Aayan")
↓
__construct()
↓
$this->name = Aayan
Multiple Parameters
class Player {
public string $name;
public int $money;
public string $rank;
public function __construct(
string $name,
int $money,
string $rank
) {
$this->name =
$name;
$this->money =
$money;
$this->rank =
$rank;
}
}
Usage
$player =
new Player(
"Aayan",
5000,
"Owner"
);
Constructor Property Promotion
PHP 8 introduced Constructor Property Promotion.
Instead of:
class Player {
private string $name;
public function __construct(
string $name
) {
$this->name =
$name;
}
}
You can write:
class Player {
public function __construct(
private string $name
) {
}
}
Benefits
✅ Less code
✅ Cleaner classes
✅ Easier maintenance
Large Example
class Database {
public function __construct(
private string $host,
private string $user,
private string $password,
private string $database
) {
}
}
Constructor Defaults
public function __construct(
private string $rank =
"Player"
) {
}
Usage:
$player =
new Player();
Rank automatically becomes:
Player
Named Arguments
PHP 8+
$player =
new Player(
name: "Aayan",
money: 5000,
rank: "Owner"
);
Validation Inside Constructors
Example:
class Player {
public function __construct(
private int $money
) {
if (
$money < 0
) {
throw new Exception(
"Money cannot be negative"
);
}
}
}
Constructor Overloading
PHP does NOT support multiple constructors.
Invalid:
__construct()
__construct(string $name)
Alternative
Use optional parameters.
public function __construct(
?string $name = null
) {
}
Factory Methods
Another alternative:
Player::create();
Example:
class Player {
public static function create(
string $name
): self {
return new self(
$name
);
}
}
Usage:
$player =
Player::create(
"Aayan"
);
Constructor Chaining
Classes may call parent constructors.
Example:
class Human {
public function __construct() {
echo "Human";
}
}
Child:
class Player
extends Human {
public function __construct() {
parent::__construct();
echo " Player";
}
}
Output:
Human Player
Why Parent Constructors Matter
Example:
Entity
↓
Human
↓
Player
Each class initializes different things.
PocketMine Example
Simplified:
Entity Constructor
↓
Human Constructor
↓
Player Constructor
Dependency Injection
One of the most important concepts.
Instead of:
class PlayerManager {
private Config $config;
public function __construct() {
$this->config =
new Config();
}
}
Use:
class PlayerManager {
public function __construct(
private Config $config
) {
}
}
Benefits
✅ Easier testing
✅ Easier maintenance
✅ Lower coupling
Real World Example
class UserService {
public function __construct(
private Database $database,
private Logger $logger
) {
}
}
Constructor Injection Flow
Database
Logger
↓
UserService
Object Composition
Objects can receive objects.
Example:
class Server {
public function __construct(
private WorldManager $worldManager
) {
}
}
Destructors
Destructors are another special method.
Executed when object is destroyed.
Syntax:
public function __destruct() {
}
Lifecycle
new Object
↓
Object Used
↓
Object Destroyed
↓
__destruct()
Example
class Test {
public function __destruct() {
echo "Destroyed";
}
}
When Does Destructor Run?
Usually:
- End of script
- Object unset
- Garbage Collection
Example
$test =
new Test();
unset(
$test
);
Output:
Destroyed
Destructor Usage
Useful for:
- Closing files
- Closing sockets
- Saving cache
- Logging
Example
class Database {
public function __destruct() {
$this->connection
->close();
}
}
Real PocketMine Usage
Examples:
Network Sessions
File Streams
Database Connections
Async Tasks
Constructor vs Destructor
| Constructor | Destructor |
|---|---|
__construct() | __destruct() |
| Runs on creation | Runs on destruction |
| Initialize object | Cleanup object |
Memory Flow
new Player()
↓
Constructor
↓
Object Active
↓
Destroy
↓
Destructor
Common Beginner Mistakes
Forgetting Parent Constructor
Bad:
class Player
extends Human {
public function __construct() {
}
}
May break initialization.
Huge Constructors
Bad:
__construct()
500 lines...
Keep constructors simple.
Heavy Logic
Avoid:
database queries
network requests
large loops
inside constructors.
Using Destructor for Important Saves
Destructor execution timing may vary.
Prefer explicit:
save();
Best Practices
✅ Keep constructors small.
✅ Use Dependency Injection.
✅ Prefer property promotion.
✅ Validate constructor arguments.
✅ Use destructors only for cleanup.
Exercises
Exercise 1
Create:
class Car {
public function __construct(
private string $brand
) {
}
}
Exercise 2
Create:
Player
Properties:
name
money
rank
Initialize using constructor.
Exercise 3
Create:
Database
Destructor should close connection.
Mini Project
Create:
class Server {
public function __construct(
private string $name,
private int $port,
private int $maxPlayers
) {
}
}
Quiz
Which method runs automatically on object creation?
Answer
__construct()
Which method runs on destruction?
Answer
__destruct()
Which PHP version introduced property promotion?
Answer
PHP 8.0
Which concept passes dependencies through constructors?
Answer
Dependency Injection
Real PocketMine Examples
new Config(...)
new Position(...)
new Item(...)
new World(...)
new Vector3(...)
Every one of these internally uses constructors.
References
https://www.php.net/manual/en/language.oop5.decon.php
Next Chapter
➡ The $this Keyword
➡ Access Modifiers
➡ Encapsulation ➡ Inheritance