php中__construct和以类名为函数名的函数同时存在时,调用那个构造函数?是调用和类名一样的那个函数吗?最好有代码荔枝,谢谢!
For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class.
以上摘自PHP文档——类与对象
意思就是,为了兼容php3和4,在PHP5中,__construct()找不到时候,会去调用类的同名函数。
同时:
Warning Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.
旧的构造函数方式在php7中已经是过时的,会在以后版本移除。所以你任何时候都应该使用 __construct()。
<?php
/**
*
*/
class Test
{
function __construct()
{
echo "I`m __construct";
}
// DEPRECATED
function Test() {
echo "I`m func which has the same name with Class ";
}
}
new Test();//我的版本是php7.1.2 输出I`m __construct
?>
__construct()
实例化对象时被调用,
当__construct和以类名为函数名的函数同时存在时,__construct将被调用,另一个不被调用。
之前我也查过这个问题,参考博客:
http://www.leixuesong.cn/2511
代码已补充. 经过测试.
<?php
//为了测试 同名函数和__construct谁先被调用
class test
{
public function __construct()
{
var_dump('张三');
}
public function test()
{
var_dump('三');
}
}
new test();