__construct()vs SameAsClassName()用于PHP中的构造函数 [英] __construct() vs SameAsClassName() for constructor in PHP

查看:138
本文介绍了__construct()vs SameAsClassName()用于PHP中的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 __ construct()而不是PHP中的构造函数的名称有什么优势吗?

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

example:

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

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


推荐答案

我同意gizmo,优点是,如果你重命名,你不必重命名你的班。 DRY。

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.

另请注意


从PHP 5.3.3开始,与命名空间类名称的最后一个元素同名的方法将不再被视为构造函数。此更改不会影响未命名的类。

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://php.net/manual/en/language.oop5.decon.php

这篇关于__construct()vs SameAsClassName()用于PHP中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆