php 命名空间使用使用问题

potency 2014-03-20 09:38:51
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
...全文
234 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2014-03-20
  • 打赏
  • 举报
回复
namespace test1;
include 'test1.php';
function test2()
{
    echo __FUNCTION__;
}
echo test();
potency 2014-03-20
  • 打赏
  • 举报
回复
to xuzuning 多谢。 为什么不用use 呢?用use也出错。 在test2.php中顶部声明 namespace test1; 也还是不能直接使用 echo test();
xuzuning 2014-03-20
  • 打赏
  • 举报
回复
include 'test1.php';
//use test1;
function test2()
{
    echo __FUNCTION__;
}
echo test1\test();
kanenaruto 2014-03-20
  • 打赏
  • 举报
回复
正如版主的例子 在用use的时候要像下面这样: use test1\test as test2; 或者 use test1\test; 这个 其实相当与 use test1\test as test; 上面的test1是命名空间后面跟着的test是test1命名下的test类 然后实例化 new test() 等价与 new test1\test(); 这个就是use的作用,就是别名的意思。
xuzuning 2014-03-20
  • 打赏
  • 举报
回复
include "test1.php";
use test1\test;

$t = new test();
echo $t->test1();
或者
include "test1.php";
use test1\test as test2;

$t = new test2();
echo $t->test1();
或者
include "test1.php";

$t = new test1\test();
echo $t->test1();
potency 2014-03-20
  • 打赏
  • 举报
回复
to @kmd007 @xuzuning 多谢。 test1.php
  
<?php
namespace test1;
class test
{
    function test1()
    {
        echo 'fun:'.__FUNCTION__;
    }
}
  
test2.php:
<?php
use test1;
include "test1.php";
$t=new test();
echo $t->test1();
感觉use还是没有起作用。
kanenaruto 2014-03-20
  • 打赏
  • 举报
回复
函数和常量是不支持use导入规则的,只有类能支持导入规则。 而且use test1;这种写法本身就是不对的。 像use test1/classname 这种写法才行,下面实例化函数的时候 new classname; //php会在test1命名空间下找classname的类,如果没有找到就自动装载了。

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧