php同名构造函数,php中__construct和以类名为函数名的函数同时存在时,调用那个构造函数?...

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值