namespace test1; include 'test1.php'; function test2() { echo __FUNCTION__; } echo test();
函数和常量是不支持use导入规则的,只有类能支持导入规则。 而且use test1;这种写法本身就是不对的。 像use test1/classname 这种写法才行,下面实例化函数的时候 new classname; //php会在test1命名空间下找classname的类,如果没有找到就自动装载了。
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还是没有起作用。
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();
正如版主的例子 在用use的时候要像下面这样: use test1\test as test2; 或者 use test1\test; 这个 其实相当与 use test1\test as test;上面的test1是命名空间后面跟着的test是test1命名下的test类 然后实例化 new test() 等价与 new test1\test(); 这个就是use的作用,就是别名的意思。
//use test1;
function test2()
{
echo __FUNCTION__;
}
echo test1\test();
为什么不用use 呢?用use也出错。
在test2.php中顶部声明 namespace test1; 也还是不能直接使用 echo test();
include 'test1.php';
function test2()
{
echo __FUNCTION__;
}
echo test();
而且use test1;这种写法本身就是不对的。
像use test1/classname 这种写法才行,下面实例化函数的时候
new classname; //php会在test1命名空间下找classname的类,如果没有找到就自动装载了。
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还是没有起作用。
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();
use test1\test as test2;
或者
use test1\test; 这个 其实相当与 use test1\test as test;上面的test1是命名空间后面跟着的test是test1命名下的test类
然后实例化 new test() 等价与 new test1\test();
这个就是use的作用,就是别名的意思。