34. The Constructor (__construct) and Destructor (__destruct)
PHP provides special magic methods that run automatically at key points in an object's lifecycle.
The Constructor (__construct)
The constructor is a method automatically called when a new object is created using new ClassName(). It is used to initialize the object's state (setting initial properties).
php
<?php class DatabaseConnection { private $host; private $user; // The constructor takes parameters needed for initialization public function __construct($host, $user) { $this->host = $host; $this->user = $user; echo "<p>Connection object created for host: $this->host</p>"; } public function getConnectionInfo() { return "Host: $this->host, User: $this->user"; } } // When instantiating, we must provide the required arguments $db = new DatabaseConnection("localhost", "root"); echo $db->getConnectionInfo(); ?>The Destructor (__destruct)
The destructor is automatically called when the object is destroyed or when the script execution ends. It's often used for cleanup tasks, such as closing files or database connections.
php
<?php class FileHandler { public function __destruct() { echo "<p>FileHandler object is being destroyed. Closing all file streams...</p>"; } public function __construct() { echo "<p>FileHandler initialized.</p>"; } } $handler = new FileHandler(); // Script continues... // The destructor runs here automatically when $handler goes out of scope. ?>