热搜:NVER node 开发 php

php namespace与use的问题

2024-09-03 16:50:02
php namespace与use的问题

/test文件夹下建立C.php文件,内容
<?php
namespace Test\Driver;
class C
{
function test()
{
echo "c";
}
}

?>

/下建立test.php文件,内容
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 
无标题文档


<?php
include "test/C.php"; 
use Test\Driver;
$c=new C();
$c->test();
echo "
"; 
 
?>





运行错误:
( ! ) 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 


回复讨论(解决方案)

如果test.php文件

include "test/C.php"; 
$c=new Test\Driver\C();
$c->test();
echo "
"; 

这么写的话,就可以正常的显示出来



的内容

include "test/C.php"; use Test\Driver as p;$c=new p\C();$c->test();

恩,这样写是可以的。但是必须要这么写吗?

不好意思,请问use 不是引用当前的命名空间里了吗?

这样子也可以

namespace Test\Driver;include "test/C.php"; $c=new C();$c->test();


use 是引用命名空间
正确的用法我也不是很清楚

引用空间名,不是把命名空间下的类都引用过来了吗?
不是在这个命名空间下的类,都可以直接的使用吗?

现在操作上,感觉use没起到什么作用。

刚才恶补了一下,现炒现卖
使用命名空间的三种方法

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();

引用空间名,不是把命名空间下的类都引用过来了吗?
只要你 include 了,里面的所用类就都加载了

什么选择性载入是不存在的,自欺欺人的

第一种和第三种我都明白

include "test/C.php";  
use Test\Driver; 
$c=new Driver\C();   就是不明白这里的Driver 是什么意思
$c->test();

你的命名空间是 Test\ Driver
$c=new  Driver\C(); 只需取命名空间的最后一节即可

呀,手欠做了个试验


<?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 "
"; 
 
?>

这样写又报错了


include "test/C.php"; 
//use Test\Driver;
$c=new Driver\C();
$c->test();
echo "
"; 


报错信息
( ! ) 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