Why does PHP 5 use __contruct () instead of className () as a constructor?

Why should I use function __construct() instead of function className() in PHP 5?

+7
oop php
source share
6 answers

I assume that by the time the object-oriented feature was added to PHP, the designers were looking at Python.

+2
source share

The magic methods / functions __ seem to be a consistent topic in PHP (this time!). One of the advantages of using __construct() over ClassName() as a constructor is changing the class name, you do not need to update the constructor.

+27
source share

Because php5 wanted to be more like python.

I baby I ...

Having a standard method for standard actions such as construction is a smart solution. For the same reason as in C # classes, when you extend a class, you use base to call base class constructors instead of a named object: it simplifies the code and simplifies maintenance.

+4
source share

Since it was unified using the __destruct () method and other special methods starting with two underscores, for example, __get, __sleep, __serialize http://us2.php.net/manual/en/language.oop5.magic.php

+4
source share

Thus, you can always call the constructor from the super (base-) class without knowing its name. This is very useful for maintaining a class tree because you do not want to update all your classes just because you are ordering class trees

and ... just guessing .. if all classes call their constructors identically __construct (), theoretically the constructor can be inherited from the superclass without any required definition. This makes sense in class trees, where intermediate abstract classes exist, and in constructions like the C object, where the default constructor behavior comes entirely from the class metadata, and therefore (in priciple!) No coding is required at all.

+1
source share

Old question, but I will bite, since no one really answered the actual question.

function className () - constructor in the style of PHP4 .

function __construct () is a PHP5-style constructor .

You must use the latter because the former is outdated and can be removed from the language.

In addition, the former may ignore various PHP5 OO concepts, such as public / private visibility operators. Not that you would like to make the constructor private if you did not use Singleton or Factory templates.

0
source share

All Articles