您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php的类里可以有两个构造函数?

2025/8/17 22:44:44发布29次查看
class ecs_error{ var $_message = array(); var $_template = ''; var $error_no = 0; /** * 构造函数 * * @access public * @param string $tpl * @return void */ function __construct($tpl) { $this->ecs_error($tpl); } /** * 构造函数 * * @access public * @param string $tpl * @return void */ function ecs_error($tpl) { $this->_template = $tpl; }

已经有了一个__construct(), 还有一个跟类名同名的构造函数ecs_error();
为什么要有两个构造函数?是为了匹配不同的版本吗?
回复内容: class ecs_error{ var $_message = array(); var $_template = ''; var $error_no = 0; /** * 构造函数 * * @access public * @param string $tpl * @return void */ function __construct($tpl) { $this->ecs_error($tpl); } /** * 构造函数 * * @access public * @param string $tpl * @return void */ function ecs_error($tpl) { $this->_template = $tpl; }

已经有了一个__construct(), 还有一个跟类名同名的构造函数ecs_error();
为什么要有两个构造函数?是为了匹配不同的版本吗?
应该是的,php4 是用的同名函数做构造函数,而 php5 用的是 __construct,具体请参考:
http://php.net/manual/zh/language.oop5.decon.php
http://php.net/manual/zh/oop4.constructor.php
应该不是吧,里面的语句都不一样,至于为啥这么写就不知道了
php4 沿袭 c++ 以类名的同名函数作为构造函数
php5 新增了 __construct 作为构造函数
由于你的类属性定义是 php4 风格的,所以可认为这个类是在 php4 基础上的扩展
并非向下兼容,而是画蛇添足
这个是为了兼容
在php4中构造函数采用与类同名的方式进行定义
在php5中构造函数采用__construct定义
在php4中不识别__construct,不影响程序正常运行
在php5中,当二者同时存在时,__construct优先
关于php的一些知识可以看下视频教程的,很多应该都有讲到
v8视频 有很多编程方面的视频教程 v8视频
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product