【问题标题】:PHP namespace & constructor issuesPHP 命名空间和构造函数问题
【发布时间】:2014-05-02 15:04:52
【问题描述】:
我正在尝试以下方法:
//file1.
namespace foo;
class mine {
public function mine() {
echo "Does not work!!";
}
}
//file2.
use foo/mine;
include "foo/mine.php";
$obj = new mine();
上述方案不起作用。没有错误,包括文件——没有调用构造函数。
但是,当我使用 __constructor() 时,一切正常。我正在使用 php v5.4
【问题讨论】:
标签:
php
constructor
namespaces
【解决方案1】:
来自php manual:
为了向后兼容,如果 PHP 5 找不到 __construct()
给定类的函数,并且该类没有从
父类,它将搜索旧式构造函数,
以班级的名义。实际上,这意味着唯一的情况
如果类有一个方法,就会有兼容性问题
命名为 __construct() 用于不同的语义。
从 PHP 5.3.3 开始,与 a 的最后一个元素同名的方法
命名空间的类名将不再被视为构造函数。这
更改不会影响非命名空间类。
您可以使用类的名称作为构造函数(除非该类是命名空间的),因为 PHP5 保留此名称是为了与 PHP4 向后兼容,但不推荐这样做,因为它是旧方式,可能会在较新版本的 php 中删除.因此,除非您正在编写一些出于某种原因需要与 PHP4 兼容的内容,否则请使用 __construct()。
【解决方案2】:
以下是命名空间\构造函数问题的 2 种不同可能解决方案
//parentclass.php
class parentclass
{
public function __construct()
{
//by default, strip the namespace from class name
//then attempt to call the constructor
call_user_func_array([$this,end(explode("\\",get_class($this)))],func_get_args());
}
}
//foo/bar.php
namespace foo;
class bar extends \parentclass
{
public function bar($qaz,$wsx)
{
//...
}
}
$abc = new foo\bar(1,2);
和
//parentclass.php
class parentclass
{
public function __construct()
{
//by default, replace the namespace separator (\) with an underscore (_)
//then attempt to call the constructor
call_user_func_array([$this,preg_replace("/\\/","_",get_class($this))],func_get_args());
}
}
//foo/bar.php
namespace foo;
class bar extends \parentclass
{
public function foo_bar($qaz,$wsx)
{
//...
}
}
$abc = new foo\bar(1,2);