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

面向对象中PHP构造方法的识别

2025/6/1 15:18:17发布17次查看
众所周知,由于历史原因,php之前是使用类名作为构造函数,在php 5中引入的新的构造函数__construct。为了实现向后兼容性,如果php 5在类中找不到 __construct() 函数,它就会尝试寻找旧式的构造函数,也就是和类同名的函数。
因此唯一会产生兼容性问题的情况是:类中已有一个名为 __construct() 的方法,但它却又不是构造函数。有如下一段代码:
builtin_functions, &class_entry->function_table, module_persistent tsrmls_cc);         //zend_api.c 1795行    /* look for ctor, dtor, clone    * if it's an old-style constructor, store it only if we don't have    * a constructor already.    */    if ((fname_len == class_name_len) && !memcmp(lowercase_name, lc_class_name, class_name_len+1) && !ctor) {     ctor = reg_function;    } else if ((fname_len == sizeof(zend_constructor_func_name)-1) && !memcmp(lowercase_name, zend_constructor_func_name, sizeof(zend_constructor_func_name))) {     ctor = reg_function;    }          scope->constructor = ctor; //在1961行 确认构造函数  
以上代码为php 5.3.0版本
从以上跟踪流程来看,程序在注册所有函数时,如果存在__construct(即zend_constructor_func_name)时,会覆盖class_name(类名)的构造函数,使其作为常规的成员函数存在。如下所示代码:
php   class foo {             public function foo() {            echo 'foo';        }             public function __construct() {            echo '__construct';        }    }         $foo = new foo();    $foo->foo();  
对于在前面的示例中的报错,我们可以在zend/zend_object_handlers.c 1057行zend_api union _zend_function *zend_std_get_constructor(zval *object tsrmls_dc)找到出处。
该用户其它信息

VIP推荐

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