In PHP, __construct initializes an object, while __destruct cleans it up. Neither method can have a return type, and any value they return is ignored. The new keyword always returns the created object, and PHP automatically calls the destructor when the object is released.
Since PHP 8.6, returning a value from __construct or __destruct is deprecated. Consider the following class which returns the result of opening and closing a log file:
Logger.php
<?php
class Logger
{
private $handle;
public function __construct(string $path)
{
$this->handle = fopen($path, 'ab');
return $this->handle !== false;
}
public function __destruct()
{
return fclose($this->handle);
}
}
<?php
require_once 'Logger.php';
$logger = new Logger('app.log');
Output:
Deprecated: Returning a value from a constructor is deprecated in Logger.php on line 11
Deprecated: Returning a value from a destructor is deprecated in Logger.php on line 16
Both deprecations are raised where the methods are declared, as soon as Logger.php is compiled. A class which is never instantiated produces them as well.
The expression new Logger('app.log') evaluates to the object no matter what the constructor returns, which is what made the practice confusing. A return statement without a value is still allowed in both methods, so a constructor or a destructor can still leave early to skip the remaining logic.
The example can be fixed by removing the return statements. A constructor which needs to report a failure can throw an exception instead:
Logger.php
<?php
class Logger
{
private $handle;
public function __construct(string $path)
{
$handle = fopen($path, 'ab');
if ($handle === false) {
throw new RuntimeException('Unable to open the log file');
}
$this->handle = $handle;
}
public function __destruct()
{
fclose($this->handle);
}
}
Leave a Comment
Cancel reply