Starting from PHP 7, using a method with the same name as its class as a constructor is considered deprecated. While this was a valid approach in earlier versions of PHP, it is no longer recommended due to changes in the language's internal behavior and best practices.
In PHP 5 and older, developers could define a constructor by naming a method the same as the class. For example:
class MyClass {
function MyClass() {
// Constructor logic
}
}
However, from PHP 7 onward, this approach triggers the following warning:
Deprecated: Methods with the same name as their class will not be constructors
This warning indicates that the method will not be treated as a constructor in future versions, even if it still works now.
To eliminate this deprecated warning, you can choose from the following solutions based on your project requirements.
The best and most future-proof solution is to rename the constructor to the built-in __construct() method, like so:
class MyClass {
function __construct() {
// Constructor logic
}
}
This method is universally supported and aligns with modern PHP coding standards.
If you're maintaining older codebases and need to support multiple PHP versions, you can use version checks:
class MyClass {
function MyClass() {
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
// Constructor logic for PHP 7+
} else {
// Constructor logic for versions below PHP 7
}
}
}
This approach helps maintain backward compatibility but is not recommended for new development.
Although this method does not suppress the warning, adding PHPDoc comments helps clarify the method’s role to other developers:
class MyClass {
/**
* MyClass constructor.
*/
function MyClass() {
// Constructor logic
}
}
While this doesn’t fix the deprecation itself, it improves code readability and documentation.
If you encounter the warning Deprecated: Methods with the same name as their class will not be constructors, consider using one of the following solutions:
Transitioning to the __construct() method ensures cleaner, more maintainable, and future-proof PHP code as the language continues to evolve.