Constructor / Destructor
Last updated
What is Constructor / Destructor?
Constructor and Destructor methods are fundamental components of Object-Oriented Programming (OOP) in PHP. A constructor is a special type of method that automatically runs upon creating an object, often used to set property values or default behaviors. On the other hand, a destructor is a method that is automatically invoked when an object is due to be destroyed, perfect for cleanup activities. Here is a basic example:
class TestClass {
public $value;
// Constructor Method
public function __construct($val) {
$this->value = $val;
}
// Destructor Method
public function __destruct() {
echo "Object is being destroyed.";
}
}
$obj = new TestClass("Hello World");
echo $obj->value;
// Displays: Hello World
// And when the script ends, "Object is being destroyed."
Free resources to learn Constructor / Destructor
- Official docsPHP Constructors and Destructors
More in stage 11: OOP Fundamentals
- OOP Fundamentals
- Classes and Objects
- Properties and Methods
- Access Specifiers
- Static Methods and Properties
- Inheritance
- Input Validation
- SQL Injection
- XSS Prevention
- CSRF Protection
- Password Hashing
- Auth Mechanisms
- Sanitization Techniques
- PDO
- MySQLi
- Object-Relational Mapping (ORM)
- Database Transactions
- Connection Pooling
- Performance Optimization
- Database Migrations
Constructor / Destructor: common questions
Can I learn Constructor / Destructor in Hindi?
This lesson is written in English. Once you sign in, open it in the interactive course and ask the AI tutor to explain Constructor / Destructor in Hindi or Hinglish. The tutor answers from this lesson’s own text, so it stays on the syllabus, and it runs on your own Google, OpenAI or Anthropic key.
Is this Constructor / Destructor tutorial for beginners?
It is lesson 62 of 120 in the free PHP roadmap, in stage 11, OOP Fundamentals. If you are new to PHP, start from stage 1 and come back here in order; if you already know the earlier stages, this lesson stands on its own.