__construct 和与类同名的函数有什么区别? [英] What's difference between __construct and function with same name as class has?

查看:32
本文介绍了__construct 和与类同名的函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
__construct 的作用是什么?

__construct 函数和与类同名的函数有什么区别吗?

is there any difference between __construct function and function with same name as class has?

class foo {
    function foo ($something){
        echo "I see ".$something." argument";
    }
}

class bar {
    function __construct ($something){
        echo "<br />
            I see ".$something." argument again";
    }
}

$foo = new foo("foo");
$bar = new bar("bar");

推荐答案

命名的方法是 PHP4 中构造函数的方式.

The method named is the PHP4 way of doing a constructor.

为了向后兼容,如果 PHP 5 找不到给定类的 __construct() 函数,它将通过类名搜索旧式构造函数.实际上,这意味着唯一会出现兼容性问题的情况是该类是否有一个名为 __construct() 的方法,该方法用于不同的语义.

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.

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

这篇关于__construct 和与类同名的函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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