Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

__construct() vs SameAsClassName() for constructor in PHP

Is there any advantage to using __construct() instead of the class's name for a constructor in PHP?

Example (__construct):

class Foo {
    function __construct(){
        //do stuff
    }
}

Example (named):

class Foo {
    function Foo(){
        //do stuff
    }
}

Having the __construct method (first example) is possible since PHP 5.

Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...