日期:2014-05-16  浏览次数:20484 次

php 命名空间使用使用问题
本帖最后由 potency 于 2014-03-20 09:46:47 编辑
test1.php:
<?php
namespace test1;
function test()
{
    echo __FUNCTION__;
}
[/code]

test2.php


<?php
use test1;
function test2()
{
    echo __FUNCTION__;
}
echo test1();

这2个php文件都在同一个子目录 test 下面。
在浏览器里运行http://localhost/test/test2.php 出现如下错误:
----------

( ! ) Warning: The use statement with non-compound name 'test1' has no effect in E:\wamp\Apache\htdocs\robot\test\test2.php on line 6

( ! ) Fatal error: Call to undefined function test1() in E:\wamp\Apache\htdocs\robot\test\test2.php on line 11
Call Stack
# Time Memory Function Location
1 0.0020 134912 {main}( ) ..\test2.php:0

--------------
很奇怪。有人知道是什么问题吗?我php是5.4

------解决方案--------------------
include 'test1.php';
//use test1;
function test2()
{
    echo __FUNCTION__;
}
echo test1\test();

------解决方案--------------------
namespace test1;
include 'test1.php';
function test2()
{
    echo __FUNCTION__;
}
echo test();

------解决方案--------------------
函数和常量是不支持use导入规则的,只有类能支持导入规则。
而且use test1;这种写法本身就是不对的。
像use test1/classname 这种写法才行,下面实例化函数的时候
new classname; //php会在test1命名空间下找classname的类,如果没有找到就自动装载了。

------解决方案--------------------
正如版主的例子 在用use的时候要像下面这样:
use test1\test as test2; 
或者
use test1\test; 这个 其实相当与 use test1\test as test;

上面的test1是命名空间后面跟着的test是test1命名下的test类
然后实例化 new test() 等价与 new test1\test();
这个就是use的作用,就是别名的意思。