Computer >> Computer tutorials >  >> Programming >> PHP

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


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.

Example

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

Output

The class "myclass" was initiated!
In SubClass constructor

Note

"__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.