Maison  >  Article  >  développement back-end  >  php 命名空间使用使用有关问题

php 命名空间使用使用有关问题

WBOY
WBOYoriginal
2016-06-13 11:54:191172parcourir

php 命名空间使用使用问题

本帖最后由 potency 于 2014-03-20 09:46:47 编辑 test1.php:
namespace test1;
function test()
{
    echo __FUNCTION__;
}
[/code]

test2.php

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

这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';<br />//use test1;<br />function test2()<br />{<br />    echo __FUNCTION__;<br />}<br />echo test1\test();

------解决方案--------------------
namespace test1;<br />include 'test1.php';<br />function test2()<br />{<br />    echo __FUNCTION__;<br />}<br />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的作用,就是别名的意思。
Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:help~iteye 求下载 不用分Article suivant:代码求简单化