I have recently started php and was wondering the differences between __construct() and having a method with the same name as the class?
Is there a reason for using it? All I can work out is it overrides the method named Foo or is it down to which you prefer?
E.g.
class Foo {
function Foo()
{
echo 'Foo stated<br>';
}
function __construct() {
echo 'Construct started<br>';
}
}
Thanks
PHP - The __construct FunctionA constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!
Ans. A member function with the same name as its class is called constructor and it is used to initialize the objects of that class type with a legal initial value.
in simple words a class is like a blueprint and defines the framework that other objects can inherit, a constructor is something that actually creates the object in the program whereas the class only gives the guidelines.
__construct() is the method name for the constructor. The constructor is called on an object after it has been created, and is a good place to put initialisation code, etc. class Person { public function __construct() { // Code called for each new Person we create } } $person = new Person();
Using __construct()
is the newer PHP5 more OOP focused method to call a constructor. Using a method with the same name as the class is the old deprecated way to do it, and it will not function as a constructor as of PHP 5.3.3 for namespaced classes.
From the constructors and destructors page:
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.
Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.
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.
"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."
Source: http://www.php.net/manual/en/language.oop5.decon.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With