

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- Is there any alternative solution for static constructor in java?
- Why the constructor name is same as the class name in Java?
- Instead of using a semicolon (;) terminator symbol, is there any other built-in-commands which execute the MySQL query?
- What is the super() construct of a constructor in Java?
- Is there any alternative for CONCAT() in MySQL?
- Is there any precautionary medicine available for Dengue?
- Is there any alternative for OpenCV imshow() method in Java?
- Should a constructor always have the same name as the class in java?
- Construct the minimum DFA for any given finite automata.
- Is there any tool that can convert an XSD file to a Python class as JAXB does for Java?
- Is there any Python object inspector?
- What is the difference between simple name, canonical name and class name in a Java class?
- Can we define constant in class constructor PHP?
- How to call parent constructor in child class in PHP?
- What is the advantage of believing in God?
Advertisements