因此唯一會產生兼容性問題的情況是:類中已有一個名為 __construct() 的方法,但它卻又不是構造函數。有如下一段代碼:
- <?PHP
- class Foo {
- public function Foo() {
- }
- private function __construct() {
- }
- }
- new Foo();
- dIE();
此時,輸出為:
Fatal error: Call to private Foo::__construct() from invalid context
此時,PHP識別出來的構造函數是__construct,因為是private,於是在外部調用出錯。好吧,我們從PHP的C源碼中查找一下原因吧。從SQL的擴展類中直接查找類的定義開始:
- spl_iterators.c 3228行 REGISTER_SPL_STD_CLASS_EX(IteratorIterator, spl_dual_it_new, spl_funcs_IteratorIterator);
- ///spl_functions.h 31行
- #define REGISTER_SPL_STD_CLASS_EX(class_name, obj_ctor, funcs) \
- spl_register_std_class(&spl_ce_ ## class_name, # class_name, obj_ctor, funcs TSRMLS_CC);
- //spl_functions.c 41行
- PHPAPI void spl_register_std_class(zend_class_entry ** ppce, char * class_name, void * obj_ctor, const zend_function_entry * function_list TSRMLS_DC)
- //spl_functions.c 2235行
- ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry TSRMLS_DC) /* {{{ */
- //調用do_register_internal_class函數
- //zend_API.c 2169行
- static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, zend_uint ce_flags TSRMLS_DC) /* {{{ */
- //調用
- zend_register_functions(class_entry, class_entry->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)找到出處。