What's difference between __construct and function with same name as class has?
The method named is the PHP4 way of doing a constructor.
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
http://www.php.net/manual/en/language.oop5.decon.php
__construct() vs SameAsClassName() for constructor in PHP
I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY.
Similarly, if you have a child class you can call
parent::__construct()
to call the parent constructor. If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.
It seems like a small thing, but missing changing the constructor call name to your parents classes could create subtle (and not so subtle) bugs.
For example, if you inserted a class into your heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.
Also note that
As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
Source: http://php.net/manual/en/language.oop5.decon.php
Difference between two classes __construct()
Your two examples may indeed seem equivalent, but from a single (yours, now) perspective only.
class Person { // First case : using the constructor
public function __construct($person) {
echo $person;
}
}
// ----------------------------------------------------------------
$person = new Person('Name');
In this example, you make it very clear that each and every object of class Person
(or one of its subclasses) must be given a name as soon as it is created. There won't ever be a Person
without a name, at any point in time. That's a design constraint you choose to impose on yourself (if you intend to create objects of class Person
) or others, in the case you are sharing your code in one way or another. If one attempts to violate this constraint, PHP will hang with an explicit error/warning message. (demo : https://3v4l.org/hCXZ8)
class Person { // Second case : no constructor (equivalent to an empty constructor)
public function name($name) {
echo $name;
}
}
// ----------------------------------------------------------------
$person = new Person();
$person->name('Name');
This is a different beast : you can create an object of class Person
, and you can display a name. You can also create a Person
and never display a name at all. You might not even know you can, actually, if you don't set your eyes on the class code for some reason (it is common practice to give each class a distinct file).
In both examples I drew a comment line between the class declaration and usage, because these are two different perspectives (think they can even be two different people who cannot communicate with each other). As the class author, you translate your constraints precisely into the most explicit code you can produce. As the class user, you don't want to lose time understanding the intricacies of the class you are using : you want to create objects with minimal complexity, take advantage of the functionality with minimal overhead and learning curve, and get on with your code and business.
Why is a method with the same name as the class being called automatically?
Both methods get called, when you create a new instance of this class, because the methods have the same name as the class itself and so they are the constructor of this class:
class Hello
{
public function hello()
{
echo "Hello";
}
}
class World
{
public function world()
{
echo " World";
}
}
So when you took an instance from both classes, both constructors got called.
Now when you renamed both methods to hello
only 1 method was counted as constructor and the other one was a normal method in the other class. That's why you only saw Hello
as output.
But don't use the name of the class as constructor! It will be deprecated in PHP 7. Use __construct()
.
What is the difference between a public constructor which calls a class method and a class method that calls another class method?
You can't return the handle from the constructor in that context because that would violate the defined behavior of new
. new SomeClass();
will only ever return an instance of the class, regardless of what other methods are called in the constructor.
__construct()
is a void method. It is not intended to return anything1. That doesn't mean that the other code in it doesn't get executed, just that your return
is disregarded in the context of creating a new object. This makes sense as the primary purpose for the constructor is to provide a means to pass dependencies to the object. Sometimes it is used to do additional initialization/setup of the object, but many people believe it should not do any work other than assigning the given arguments to the object's properties. Either way, there should be no need for it to return anything.
1 You can actually call the __construct()
method explicitly after you create the object, and then it will behave like a normal method and your return
will work.
$db = new HMMDatabaseHandle();
$dbh = $db->__construct();
var_dump($dbh); // PDO Object
This isn't a normal thing to do though, and I can't think of a scenario where it would be useful or desirable. I just wanted to point out that it is possible.
What is the function __construct used for?
__construct
was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor).
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
An example could go like this:
class Database {
protected $userName;
protected $password;
protected $dbName;
public function __construct ( $UserName, $Password, $DbName ) {
$this->userName = $UserName;
$this->password = $Password;
$this->dbName = $DbName;
}
}
// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );
Everything else is explained in the PHP manual: click here
Related Topics
Interface Implementation: Declaration Must Be Compatible
PHP Warning: Exec() Unable to Fork
Show Stock Status Next to Each Attribute Value in Woocommerce Variable Products
Call to Undefined Method Pdo::Execute()
Get Characters After Last/In Url
How to Create and Store Md5 Passwords in MySQL
How to Merge Two Eloquent Collections
How to Get User Timezone Using Jquery
Utf-8 Encoding for Subject in Contact Form Email
Mysql_Real_Escape_String Is Undefined
Datetime Class VS. Native PHP Date-Functions
Call Another PHP Script and Return Control to User Before the Other Script Completes
Flip Associative Array and Store New Values in Subarrays to Prevent Losing Duplicated Values