Is there any advantage to using __construct() instead of the class's name for a constructor in PHP?

PHPProgrammingServer Side Programming

Yes, there are several advantages to using the magic function __construct() instead of the class's name. Those are listed below −

  • The magic function __construct is introduced in PHP 5.4. One advantage of using __construct() over ClassName() as a constructor is if you change the name of the class, you don't need to update the constructor which supports DRY(don't repeat yourself) concept.
  • If you have a child class you can call parent::__construct()to call the parent constructor in an easy way.


 Live Demo

   class myclass{
      public function __construct(){
         echo 'The class "', __CLASS__, '" was initiated!'."\n";
   class childclass extends myclass{
      public function __construct() {
         print "In SubClass constructor ";
   $myobj = new childclass();


The class "myclass" was initiated!
In SubClass constructor


"__CLASS__" is what’s called a magic constant, which, in this case, returns the name of the class in which it is called.

Old style constructors are DEPRECATED in PHP 7.0 and will be removed in a future version. You should always use __construct() in new code.

Published on 28-Jun-2019 14:57:57