php namespace与use的问题

半支烟z 2014-03-10 12:57:41
/test文件夹下建立C.php文件,内容
<?php
namespace Test\Driver;
class C
{
function test()
{
echo "c";
}
}

?>

/下建立test.php文件,内容
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<?php
include "test/C.php";
use Test\Driver;
$c=new C();
$c->test();
echo "<br>";

?>
</body>
</html>



运行错误:
( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: Class 'C' not found in E:\hongyunlai\thinkphp32\test.php on line 14
Call Stack
# Time Memory Function Location
1 0.0006 247520 {main}( ) ..\test.php:0
...全文
728 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
Wintercoder 2015-07-02
  • 打赏
  • 举报
回复
use 使用的时候是这样用,到类名use Test\Driver\C; 然后再new C();就没问题了。
xcorp1986 2014-10-04
  • 打赏
  • 举报
回复
这个use感觉用途不是很大啊,一开始以为use了就不需要include,殊不知还是要的
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
include "test/C.php"; //use Test\Driver; $c=new Driver\C(); $c->test(); echo "<br>"; 报错信息 ( ! ) SCREAM: Error suppression ignored for ( ! ) Fatal error: Class 'Driver\C' not found in E:\hongyunlai\thinkphp32\test.php on line 14 Call Stack # Time Memory Function Location 1 0.0005 247472 {main}( ) ..\test.php:0
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
呀,手欠做了个试验 <?php namespace Test\Driver; use Test\Driver; class C { function test() { echo "c"; } } ?> test.php <?php include "test/C.php"; //use Test\Driver; $c=new Test\Driver\C(); $c->test(); echo "<br>"; ?> 这样写又报错了
xuzuning 2014-03-10
  • 打赏
  • 举报
回复
你的命名空间是 Test\Driver $c=new Driver\C(); 只需取命名空间的最后一节即可
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
第一种和第三种我都明白 include "test/C.php"; use Test\Driver; $c=new Driver\C(); 就是不明白这里的Driver 是什么意思 $c->test();
xuzuning 2014-03-10
  • 打赏
  • 举报
回复
引用 5 楼 banzhiyanz 的回复:
引用空间名,不是把命名空间下的类都引用过来了吗?
只要你 include 了,里面的所用类就都加载了 什么选择性载入是不存在的,自欺欺人的
xuzuning 2014-03-10
  • 打赏
  • 举报
回复
刚才恶补了一下,现炒现卖 使用命名空间的三种方法
include "test/C.php"; 
$c=new Test\Driver\C();
$c->test();
include "test/C.php"; 
use Test\Driver;
$c=new Driver\C();
$c->test();
include "test/C.php"; 
use Test\Driver as p;
$c=new p();
$c->test();
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
现在操作上,感觉use没起到什么作用。
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
引用空间名,不是把命名空间下的类都引用过来了吗? 不是在这个命名空间下的类,都可以直接的使用吗?
xuzuning 2014-03-10
  • 打赏
  • 举报
回复
这样子也可以
namespace Test\Driver;
include "test/C.php"; 
$c=new C();
$c->test();
use 是引用命名空间 正确的用法我也不是很清楚
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
恩,这样写是可以的。但是必须要这么写吗? 不好意思,请问use 不是引用当前的命名空间里了吗?
xuzuning 2014-03-10
  • 打赏
  • 举报
回复
include "test/C.php"; 
use Test\Driver as p;
$c=new p\C();
$c->test();
半支烟z 2014-03-10
  • 打赏
  • 举报
回复
如果test.php文件 include "test/C.php"; $c=new Test\Driver\C(); $c->test(); echo "<br>"; 这么写的话,就可以正常的显示出来 c 的内容

21,887

社区成员

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

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