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
host = $host; $this->user = $user; echo "Connection object created for host: $this->host
"; } 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
FileHandler object is being destroyed. Closing all file streams..."; } public function __construct() { echo "FileHandler initialized.
"; } } $handler = new FileHandler(); // Script continues... // The destructor runs here automatically when $handler goes out of scope. ?>