Currently, PHP supports two naming conventions for constructors. PHP 4 supported Java-style constructors:
class A
{
public function A()
{
echo "I'm a constructor for class A!";
}
}
PHP 5 supports both the Java-style constructors and a "magic method" syntax:
class A
{
public function __construct()
{
echo "I'm a constructor for class A!";
}
}
The Java-style syntax is slated for deprecation, and some features of it don't work in the latest PHP. However, it has an interesting property that I know of no analogue for with the "magic method" syntax. If derived class foobar
has no explicit constructor, then the foobar
method of the base class becomes the foobar
constructor:
class A
{
public function A()
{
echo "I'm a constructor for class A!";
}
public function B()
{
echo "I'm a constructor for class B!";
}
}
class B extends A
{
}
Since Java-style constructors are being deprecated, what will become of the set-the-constructor-in-the-parent language feature?
Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.
PHP 7 "The ASP tags <%, %>, <%=" are deprecated.
The constructor may be made private or protected to prevent it from being called externally. If so, only a static method will be able to instantiate the class. Because they are in the same class definition they have access to private methods, even if not of the same object instance.
Inheritance: As Inheritance is an object-oriented concept, the Constructors are inherited from parent class to child class derived from it. Whenever the child class has constructor and destructor of their own, these are called in order of priority or preference.
You probably learned this here, for PHP 4.
As you already know, in PHP 5 documentation (here) it is stated that if no __construct() is used or inherited, the old syntax kicks in as a fallback:
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent 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.
So the old syntax should still be valid, as PHP 5.4.11. There is no explicit plan for deprecation, right now, even if it's foreseeable.
Anyway, when (and if) they will be dropped, this feature will be dropped too as there is no way to reproduce it with the __construct() syntax.
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