PHP Constructors & Destructors
In this page:
What is a Constructor?
A constructor is a special method named __construct() that PHP calls automatically the moment an object is created with new, making it the natural place to initialize required properties or validate input.
Example: What is a Constructor?
<?php
class User {
function __construct() {
echo "User object created!";
}
}
new User();
?>
Login to try C/C++/Java/PHP code in the editor
Constructors with Parameters
Constructor parameters let you require certain data up front, such as new User(Aditi, '[email protected]'), ensuring every object starts in a valid, fully-initialized state rather than needing manual setup afterward.
Example: Constructors with Parameters
<?php
class User {
public $name;
public $email;
function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User('Aditi', '[email protected]');
echo $user->name . " " . $user->email;
?>
Login to try C/C++/Java/PHP code in the editor
Default Values in Constructors
A destructor is a special method named __destruct() that PHP calls automatically when an object is about to be destroyed, typically at the end of a script or when nothing references it anymore.
Example: Default Values in Constructors
<?php
class Logger {
function __destruct() {
echo "Logger destroyed";
}
}
$log = new Logger();
?>
Login to try C/C++/Java/PHP code in the editor
What is a Destructor?
Destructors are most useful for cleanup tasks like closing a file handle or a database connection that the object opened, so resources don't leak even if the code that created the object forgets to close them explicitly.
Example: What is a Destructor?
<?php
class FileHandler {
function __destruct() {
echo "Closing file handle";
}
}
$file = new FileHandler();
?>
Login to try C/C++/Java/PHP code in the editor
Constructor and Destructor Together
Unlike constructors, destructors are rarely written explicitly in typical PHP web code, since PHP's request lifecycle already cleans up resources at the end of each request — they matter more in long-running scripts.
Example: Constructor and Destructor Together
<?php
class Task {
function __construct() {
echo "Task started\n";
}
function __destruct() {
echo "Task finished";
}
}
$task = new Task();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: