PHP名称空间&构造问题 [英] PHP namespace & constructor issues

查看:57
本文介绍了PHP名称空间&构造问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以下方法:

//file1.
namespace foo;
class mine {
     public function mine() {
         echo "Does not work!!";
     } 
}
//file2. 

use foo/mine;
include "foo/mine.php";
$obj = new mine();

以上情况不起作用.包括文件在内没有错误-不会调用构造函数.

the above scenario is not working. No errors including the file -- constructor does not get called.

但是,当我使用__constructor()时,一切正常.我正在使用php v5.4

However when i use __constructor(), everything works fine. I am using php v5.4

推荐答案

来自 php手册:

为了向后兼容,如果PHP 5找不到__construct() 给定类的函数,并且该类没有从一个类继承一个 父类,它将搜索旧式的构造函数, 以班级名称命名.实际上,这意味着唯一的情况 可能存在兼容性问题的是,如果类具有方法 名为__construct(),用于不同的语义.

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

从PHP 5.3.3开始,与a的最后一个元素同名的方法 命名空间的类名将不再被视为构造函数.这 更改不会影响非命名空间的类.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

您可以使用该类的名称作为构造函数(除非该类具有名称空间),因为PHP5保留该名称是为了与PHP4向后兼容,但是不建议这样做,因为它是旧的方式,并且可能在较新的php版本中被删除. .因此,除非您出于某种原因要编写与PHP4兼容的东西,否则请使用__construct().

You can use the name of the class as constructor (unless the class is namespaced) because PHP5 keeps this for backwards compatibility with PHP4, but this is not recomended because it is the old way and may be removed in newer versions of php. So unless you are writting something that needs for some reason to be PHP4 compatible use __construct().

这篇关于PHP名称空间&构造问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆